How to properly use relative or absolute imports in Python modules?

Viewed 23707

Usage of relative imports in Python has one drawback, you will not be able to run the modules as standalones anymore because you will get an exception: ValueError: Attempted relative import in non-package

# /test.py: just a sample file importing foo module
import foo
...

# /foo/foo.py:
from . import bar
...
if __name__ == "__main__":
   pass

# /foo/bar.py: a submodule of foo, used by foo.py
from . import foo
...
if __name__ == "__main__":
   pass

How should I modify the sample code in order to be able to execute all: test.py, foo.py and bar.py

I'm looking for a solution that works with python 2.6+ (including 3.x).

6 Answers

You need __init__.py in each folder.

Relative import works only when you do:

python test.py

test.py imports foo.py and foo.py can relative import anything from the folder of test.py and above.

You can't do:

cd foo
python foo.py
python bar.py

It will never work.

You can try the sys.path.append or sys.path.insert solution but you gonna screw up the paths and you'll have problems with the f=open(filename).

Related