1

This may be answered somewhere else but I cannot find a solution.

I have these two folder structures:

app/
  service/
    __init__.py
    caller.py
    ...
  utils/
    __init_.py
    config.py
    ...
  __init__.py
  ...

In caller.py I have:

from app.utils import config

When I run python caller.py (from cd to app/service) I get:

from app.utils import config
ModuleNotFoundError: No module named 'app'

However, if I move caller.py to the app folder and use the following import line:

from utils import config

It works. Why? I've also tried using .app.utils, ..utils, etc., but to no avail.

ps0604
  • 1,513
  • 20
  • 113
  • 274

1 Answers1

3

If you add the parent directory to the path, then when changing into directory "/app/service", Python will find the neighboring "utils" directory.

caller.py

import sys

sys.path.insert(1, '../')

from utils import config

print(f"Caller imported config value SETTING_X: {config.SETTING_X}")

config.py

SETTING_X = 42

Output

Caller imported config value SETTING_X: 42
Christopher Peisert
  • 18,667
  • 3
  • 73
  • 100