LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Python -- Importing Modules (https://www.linuxquestions.org/questions/programming-9/python-importing-modules-4175466241/)

Eahil 06-16-2013 02:51 PM

Python -- Importing Modules
 
Hi! I'm just wondering a bit here. With importing modules in Python, I usually go about it like this when I'm using standard modules:

Code:

#Standard module
import os
#No problems at runtime

But when I'm creating my own application, the directory structure might look a bit like this:

Code:

~$ Fighting Game/
    __init__.py
    dir1/
        script1a.py
        script1b.py
        __init__.py
    dir2/
        script2a.py
        script2b.py
        __init__.py

There's no problem doing this is script1a:

Code:

import script1b
But in doing this:
Code:

import script2a
An ImportError occurs and it claims it does not exist. I've attempted relative importing, but it doesn't seem to work even with:

Code:

import ..script2b
Is there a better way than adding the package in development, to my PYTHONPATH? I'd like to simply refer to the different modules in the different directories rather than go forth with just putting everything into the system itself.

Any help with this?

NevemTeve 06-16-2013 11:14 PM

If import accepts pathnames, then use proper pathnames:

Code:

bad: import ..script2b
good:import ../dir2/script2b


ta0kira 06-17-2013 10:42 AM

Code:

script2a = __import__('dir2.script2a',level=1)
Kevin Barry

jpkotta 06-17-2013 02:30 PM

The way I usually do this is with a .pth file and the site module.

dir1/deps.pth
Code:

../dir2
dir1/script1a.py
Code:

import site
site.addsitedir('.') # picks up the paths in dir1/deps.pth

You can use relative or absolute paths in both the .pth file and addsitedir() call. The path information can live in version control and you don't have to mess with environment variables. The way I usually arrange things is to have a deps.pth in the top level and the addsitedir() in any scripts that are expected to be __main__. addsitedir() does little more than adding paths to sys.path, so if the top level script does it, all the imported modules will see the paths too.

As a bonus, you can make this work with pylint so that it finds all of your local dependencies.

.pylintrc
Code:

[MASTER]
init-hook=import site; site.addsitedir('.')



All times are GMT -5. The time now is 02:47 AM.