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()
bar
as a library rather than as a submodule to mypackage? I.e. could you refactor mypackage into mypackage1 and mypackage2 where mypackage2 (with foo) imports mypackage1 (with bar)? – jsalonen