Search code examples
pythonimportimporterrormodulenotfounderror

Import not working inside folder (Module not found / Import Error)


I have seen this question in many pages and also here but I have tried everything and I can't seem to make it work so I need a second opinion please :(

I have the following structure in my code: project structure It looks like this:

ODS/
|__init__.py
|example.py
├── mqtt_model/
│   ├── __init__.py
│   └── mqtt_class.py
└── python-can/
    ├── can-venv/
    ├── __init__.py
    ├── Dockerfile
    ├── mqtt_can_logger.py
    ├── read.py
    ├── requirements.txt
    └── write.py

What I want to do is import a class (MQTT_Model) inside mqtt_class.py to mqtt_can_logger.py

In my mqtt_model/__init__.py I have from .mqtt_class import MQTT_Model

python_can/__init__.py is an empty file and I want to import the MQTT_Model to mqtt_can_logger.py.

This import is not working but in example.py it does work with from mqtt_model import MQTT_Model It's just inside the python-can directory that's not working!

I have tried doing relative and absolute paths like:

from mqtt_model.mqtt_class import MQTT_Model
from .mqtt_model.mqtt_class import MQTT_Model

from ..mqtt_model import MQTT_Model
from .mqtt_model import MQTT_Model
from mqtt_model import MQTT_Model

Nothing works ;( i keep getting eitherI mport Error: attempted relative import with no known parent package or ModuleNotFound: no module named 'mqtt_model'


Solution

  • Edited: I assume that your import problem is caused by running your program from virtual environment created in the can-venv folder. So, the python-can folder becomes the root folder of the project. It makes interpreter unable to find the modules and packages outside this directory. To overcome this problem you should either recreate the virtual environment for you project in the ODS/ folder or add extra paths by sys.path.insert following this answer:

    import sys
    
    sys.path.insert(1, '/path/to/ODS/')
    
    # OR
    
    sys.path.insert(1, '/path/to/ODS/mqtt_model')
    

    Then, you could import modules and packages from ODS/ folder:

    from mqtt_model.mqtt_class import MQTT_Model  # sys.path.insert(1, '/path/to/ODS/')
    
    # OR
    
    from mqtt_class import MQTT_Model   # sys.path.insert(1, '/path/to/ODS/mqtt_model')