ps0604
ps0604

Reputation: 1081

ModuleNotFoundError in absolute folder structure

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.

Upvotes: 1

Views: 99

Answers (1)

Christopher Peisert
Christopher Peisert

Reputation: 24194

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

Upvotes: 3

Related Questions