[Python] Reason for no relative imports in python scripts

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

  1. Stack

    Stack Membro Participativo

    I understand that in Python, relative imports are only allowed inside of packages. Personally, I find this functionality great; it makes it very easy to import stuff from other modules.

    However, for files that are not inside a Package, relative imports are not allowed. A typical situation I encounter is in my small projects, which I often structure as follows :

    my_project/
    ├── modules/
    │ ├── __init__.py
    │ ├── module1.py
    │ └── module2.py
    ├── scripts/
    ├── script1.py
    └── script2.py


    Now, from script1.py and script2.py, I'd want to import stuff from modules, but to do so I have to resort to convoluted ways, such as sys.path.append(Path(__file__).parent.parent.as_poxis()), which feel very weird.

    It would feel very natural to just do from ..modules import whatever inside script1.py for example. I'm sure there is a good reason for why this isn't possible, but I am not sure why this is the case!

    In summary, why are relative imports not allowed in Python scripts?

    Continue reading...

Compartilhe esta Página