Python – Using Relative or Absolute Imports in Modules

modulepackagepythonpython-importpython-module

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

Code

# /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 of the following? test.py, foo.py and bar.py.

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

Best Answer

You could just start 'to run the modules as standalones' in a bit a different way:

Instead of:

python foo/bar.py

Use:

python -mfoo.bar

Of course, the foo/__init__.py file must be present.

Please also note, that you have a circular dependency between foo.py and bar.py – this won't work. I guess it is just a mistake in your example.

It seems it also works perfectly well to use this as the first line of the foo/bar.py:

#!/usr/bin/python -mfoo.bar

Then you can execute the script directly in POSIX systems.