Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ideal Way to Create a Python "Library"

I want to create a "library" of Python modules which I will be able to access from several separate project folders.

For example, I want the Python scripts in /proj1/ and /proj2/ to have access to /lib/.

/lib/help.py
/lib/more_help.py

/proj1/script.py
/proj1/script2.py

/proj2/this_script.py
/proj2/another_script.py

I don't want a single directory with all the Python scripts, as this seems rather disorganized. I also definitely don't want to copy the same /lib/ script into each of the different projects.

What is the ideal way to handle this in Python? Is it appending to Python's path? Or is this more of a hack? This seems to have the disadvantage of making the files less portable. Or is it this question/answer about using relative paths? Or something else?

I should add that I'm interested in Python 2.x rather than 3.x, if it matters.

like image 248
David C Avatar asked Aug 12 '12 05:08

David C


People also ask

How do you write a good library?

There are a few basic characteristics of a well-designed library. It should be easy to understand and use. Its behavior should be easily modifiable where that was the intent of the library author. Behaviours not intended to be modifiable should be completely hidden from users.

Can we create our own Python library?

Here, we'll decide the names and number of the modules to be included. In our case, The name of our library will be mylibrary and the basic structure of our library is shown below. We'll create this directory any where we like in our system. Step 2: Now let's write the python code for all the files.

Which Python library is easiest?

Keras is a very popular Machine Learning library for Python. It is a high-level neural networks API capable of running on top of TensorFlow, CNTK, or Theano. It can run seamlessly on both CPU and GPU. Keras makes it really for ML beginners to build and design a Neural Network.

Which library is most used in Python?

Numpy is considered as one of the most popular machine learning library in Python.


2 Answers

Turn lib/ into a package, then put it in one of the directories in sys.path (or add a new entry). You can then import e.g. lib.help into your projects.

like image 177
Ignacio Vazquez-Abrams Avatar answered Oct 14 '22 14:10

Ignacio Vazquez-Abrams


Follow the standard road that everyone takes: make your code a proper Python package with a proper setup.py. The benefits are: easy_install'able, easy distributable, easy generation of command line script (through console_scripts entry point) etc....

like image 31
Andreas Jung Avatar answered Oct 14 '22 15:10

Andreas Jung