I know that there are lots of questions about the same import issues in Python but it seems that nobody managed to provide a clear example of correct usage.
Let's say that we have a package mypackage
with two modules foo
and bar
. Inside foo
we need to be able to access bar
.
Because we are still developing it, mypackage
is not in sys.path
.
We want to be able to:
- import
mypackage.foo
- run
foo.py
as a script and execute the sample usage or tests from the__main__
section. - use Python 2.5
How do we have to do the import in foo.py in order to be sure it will work in all these cases.
# mypackage/__init__.py
...
# mypackage/foo/__init__.py
...
# mypackage/bar.py
def doBar()
print("doBar")
# mypackage/foo/foo.py
import bar # fails with module not found
import .bar #fails due to ValueError: Attempted relative import in non-package
def doFoo():
print(doBar())
if __name__ == '__main__':
doFoo()
My solution looks a bit cleaner and can go at the top, with all the other imports:
Take a look at the following info from PEP 328:
When you run
foo.py
as a script, that module's__name__
is'__main__'
, so you cannot do relative imports. This would be true even ifmypackage
was onsys.path
. Basically, you can only do relative imports from a module if that module was imported.Here are a couple of options for working around this:
1) In
foo.py
, check if__name__ == '__main__'
and conditionally addmypackage
tosys.path
:2) Always import
bar
usingfrom mypackage import bar
, and executefoo.py
in such a way thatmypackage
is visible automatically: