2

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.

Danylo Mysak
  • 1,514
  • 2
  • 16
  • 22

1 Answers1

1

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