Python 3 import relative failure
Consider the following package example:
example/
โโโ bar.py
โโโ foo.py
โโโ __init__.py
foo.py
It contains only one line of code: from . import bar
.
If I execute python foo.py
inside the package root example
I get:
SystemError: Parent module '' not loaded, cannot perform relative import
What am I doing wrong?
source to share
When you use python foo.py
, foo.py
it is not included in the module example
. Create __main__.py
to run the relevant part foo.py
(usually it shouldn't run any code at the top level), change the parent directory and try it python -m example
.
For example foo.py
:
def hello():
print('Hello, world!')
__main__.py
:
from . import foo
foo.hello()
source to share