[Python] Avoiding `sys.path.append(..)` for imports

Discussão em 'Python' iniciado por Stack, Fevereiro 8, 2025.

  1. Stack

    Stack Membro Participativo

    This isn't the first time I am cringing over imports in Python. But I guess this one is an interesting use case, so I thought to ask it here to get a much better insight. The structure of my project is as follows:

    sample_project
    - src
    - __init__.py
    - module1
    - __init__.py
    - utils.py
    - module2
    - __init__.py
    - models.py
    - app.py


    The module1 imports methods from module2 and app imports method from all the other. Also, when you run the app it needs to create a folder called logs outside of src folder. There are now to ways to run the app:

    1. From inside src folder flask run app
    2. From outside of src folder flask run src.app

    To make sure that I don't get import errors because of the change of the top level module where the app is started, I do this:

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


    Is there any better solution to this problem?

    Continue reading...

Compartilhe esta Página