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?

+3


source to share


1 answer


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()

      

+2


source







All Articles