Proper way to import from a module in Python so that it remains both importable and executable

Viewed 51

Let’s say I have 3 files:

inc/a.py:

foo = 'bar'

inc/b.py:

from a import foo

c.py:

from inc.b import foo

If I run python3 inc/b.py, everything is fine. However, when I run python3 c.py, the following error shows up: ModuleNotFoundError: No module named 'a'.

If I change inc/b.py to

from .a import foo

the command python3 c.py now runs okay, but python3 inc/b.py fails with ImportError: attempted relative import with no known parent package.

How do I structure the code so that both c.py and inc/b.py remain directly executable? I’m using Python 3.9.5.

1 Answers

The short answer is, edit your /inc/b.py to look like this:

from .a import foo

and instead of running:

python inc/b.py

run:

python -m inc.b

But this problem you are having is pretty common and answered very detailed in this post: https://stackoverflow.com/a/16985066/15906059

Related