erogol
erogol

Reputation: 13614

How to import some set of Python modules globally?

In my particular setting, I have a set of python modules that include auxiliary functions used in many different other modules. I putted them into a LIBS folder and I have other folder at the same path level those are including other modules that are doing certain jobs by using the help of these LIBS modules. Presently, I do this for all the modules to import LIBS modules.

import sys
sys.path.insert(0, '../LIBS')

import lib_module1
import lib_module2
.... 

As the project getting larger, this starts to be pain in the neck. I need to write down a large set of import statements for these auxiliary LIBS modules for each new module.

Is there any way to automatically import all these LIBS modules for the other modules that are in the folders living at the same path lelvel with LIBS folder?

Upvotes: 1

Views: 240

Answers (2)

Jonathan Eunice
Jonathan Eunice

Reputation: 22443

Indeed there is! Start treating your LIBS modules as "real" modules (or packages) that are installed into the system like any other.

This means you will have to write a setup.py script to install your code. Generally this is done inside your development directory, then your module is installed with:

$ sudo python setup.py install

This will install your module under the site-packages subdirectory of wherever Python libraries are stored on your system.

I suggest starting by copying someone else's working setup.py and supporting files, then modifying to suit your packages. For example, here is my quoter module.

Fair warning: This is a pretty big step. Not only will you learn to deploy your module locally, you can also publish it on PyPI if you wish. The step of moving to true packages will encourage you to write more and more standard documentation, to develop and run more tests, to adopt more rigorous version specifications, to more clearly identify and define code dependencies, and take many other "professionalization" steps. These all pay dividends in better, more reliable, more portable, more easily deployed code--but I'd be lying if I didn't admit the learning curve can be steep at times.

Upvotes: 0

Vimalraj Selvam
Vimalraj Selvam

Reputation: 2245

For this, you can use

 __init__.py

Kindly refer Modules and Stackoverflow.

Upvotes: 4

Related Questions