简体   繁体   中英

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

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

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.

Your hello.py is in functions folder, just add ".." in your hello.py as:

from ..models.hello_model import HttpMessageModel

It will pull the execution scope out from function folder while executing import in hello.py, thus your intended import in hello.py will work fine. I just tried it, and I can see the output.

PS: I am Ubuntu 20.04 user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM