Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python local modules

I have several project directories and want to have libraries/modules that are specific to them. For instance, I might have a directory structure like such:

myproject/
  mymodules/
    __init__.py
    myfunctions.py
  myreports/
    mycode.py

Assuming there is a function called add in myfunctions.py, I can call it from mycode.py with the most naive routine:

execfile('../mymodules/myfunctions.py')
add(1,2)

But to be more sophisticated about it, I can also do

import sys
sys.path.append('../mymodules')
import myfunctions

myfunctions.add(1,2)

Is this the most idiomatic way to do this? There is also some mention about modifying the PYTHONPATH (os.environ['PYTHONPATH']?), but is this or other things I should look into?

Also, I have seen import statements contained within class statements, and in other instances, defined at the top of a Python file which contains the class definition. Is there a right/preferred way to do this?

like image 550
hatmatrix Avatar asked Oct 11 '11 21:10

hatmatrix


People also ask

Where does Python look for local modules?

Python looks for modules in “sys. It looks for a file called a_module.py in the directories listed in the variable sys. path .

What are the 3 modules in Python?

Python Built-in Modulesprint() and input() for I/O, Number conversion functions such as int(), float(), complex(), Data type conversions such as list(), tuple(), set(), etc.


1 Answers

Don't mess around with execfile or sys.path.append unless there is some very good reason for it. Rather, just arrange your code into proper python packages and do your importing as you would any other library.

If your mymodules is in fact a part of one large project, then set your package up like so:

myproject/
    __init__.py
    mymodules/
        __init__.py
        myfunctions.py
    myreports/
        __init__.py
        myreportscode.py

And then you can import mymodules from anywhere in your code like this:

from myproject.mymodules import myfunctions
myfunctions.add(1, 2)

If your mymodules code is used by a number of separate and distinct projects, then just make it into a package in its own right and install it into whatever environment it needs to be used in.

like image 159
Mark Gemmill Avatar answered Oct 09 '22 10:10

Mark Gemmill