Home > front end >  ModuleNotFoundError: No module named in another submodule
ModuleNotFoundError: No module named in another submodule

Time:04-22

I have read a couple of threads on StackOverflow but did not find any answer that has fixed my problem. I'm pretty new to Python and cannot figure out how does modeling system works. I do understand the difference between module and package, but that does not help me with my problem. Here goes:

Here's my project structure:

venv/
root/
    commons/
        config.py
    main/
        main.py

Here's my config.py:

class Config:
...

Here's my main.py

from commons.config import Config
...

when running (venv) python3 root/main/main.py I get ModuleNotFoundError: No module named 'config'. What am I doing wrong? It is a problem with my app? with my main.py? With the way I execute my main.py?

Execution is done using Python 3.9 on MacOS

CodePudding user response:

The path to config.py is not added to the list of paths where the interpreter looks for modules and hence does find the config module.

A simple workaround is to change in main.py:

from commons.config import Config

to

from root.commons.config import Config

and execute main.py as a module in the project directory with

python -m root.main.main

When the file is executed as a module it will add the path from where it is executed to the paths the interpreter looks for modules and root.commons.config is a absolute reference from then on.

CodePudding user response:

As @Iliya mentioned, the interpreter doesn't find the way to 'config' module.

You can modify your main.py to fix the issue:

import sys
sys.path.append("absolute_path_to_root")

from commons.config import Config
...

or

import os
import sys

# set the parent dir into python's search path
current = os.path.dirname(os.path.realpath(__file__))
parent = os.path.dirname(current)
sys.path.append(parent)

from commons.config import Config
...
  • Related