Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python multi-level imports is not working

Consider this folder structure

│   main.py
│
+---src
│   +---functions
│   │   │   hello.py
│   │       
│   +---models
│       │   hello_model.py

main.py

from src.functions.hello import http_message


if __name__ == "__main__":
    print(http_message("This is a test message").message)

hello.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from models.hello_model import HttpMessageModel


def http_message(message: str) -> HttpMessageModel:
    return HttpMessageModel(
        message=message,
        code=200,
    )

hello_model.py

from dataclasses import dataclass


@dataclass
class HttpMessageModel:
    message: str
    code: int

If I launch py main.py I get this error message

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    from src.functions.hello import http_message
  File "L:\wamp64\www\GITHUB\create-python-app\src\functions\hello.py", line 1, in <module>
    from models.hello_model import HttpMessageModel
ModuleNotFoundError: No module named 'models

In this particular case how do I handle imports (with namespaces ?)

full code exemple : https://github.com/TheSmartMonkey/create-python-app

>Solution :

the solution to the problem is posted here (as a Pull Request), you are free to accept it:

create-python-app-PR

The main issue is that you are not adding src. module on the route of your module src/functions/hello.py.

Before:

from models.hello_model import HttpMessageModel

After:

from src.models.hello_model import HttpMessageModel

Also, after run the main.py (in my case using python3 main.py) I got this output:

hello world !
4
This is a test message

Also, the tests (2 in total), ends correctly, I didn’t try the coverage tests.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading