Search code examples
pythonpython-module

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?


Solution

  • 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.