Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative import failure in Python 3

Tags:

python

Consider the following example package:

example/
├── bar.py
├── foo.py
└── __init__.py

foo.py contains just one line of code: from . import bar.

If I execute python foo.py from inside the example package root, I get:

SystemError: Parent module '' not loaded, cannot perform relative import

What am I doing wrong?

like image 885
Dun Peal Avatar asked Mar 05 '26 08:03

Dun Peal


1 Answers

When you’re running python foo.py, foo.py is not part of the example module. Create __main__.py to run the relevant part of foo.py (it shouldn’t run any code at the top level, generally), change to the parent directory, and try python -m example.

For example, foo.py:

def hello():
    print('Hello, world!')

__main__.py:

from . import foo

foo.hello()
like image 61
Ry- Avatar answered Mar 06 '26 21:03

Ry-