[Python] Using Alias in __init__.py Still Exposes Original Submodule Name in Package Namespace...

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

  1. Stack

    Stack Membro Participativo

    I noticed unexpected behavior when importing a submodule with an alias in my package's __init__.py file. In short, using alias in __init__.py still exposes original submodule name in package namespace.

    Specifically, this is how to reproduce the result:

    • Files

    .
    ├── package
    │ ├── __init__.py
    │ └── submodule.py
    └── test.py

    • __init__.py

    from . import submodule as sm

    print(dir())

    • test.py

    import package


    print(package.submodule)

    • run test.py would get

    ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'sm', 'submodule']
    <module 'package.submodule' from path_to_submodule.py>

    • python version: 3.12.7
    What happens


    You can see the submodule is exposed even I import it as alias in __init__.py.

    What I expect


    I expect that the test.py should not have the access to package.submodule because the __init__.py didn't import it directly. And I am not sure if this is a bug of python.

    The point in this question is that I never import submodule directly but I can have access to it.

    I try to ask ChatGPT or other LLMs and search the doc from python.org. However, I didn't get a clear answer. Is this a bug or a normal design?

    Continue reading...

Compartilhe esta Página