TransWikia.com

Should module import structures avoid dragging intermediate modules into higher namespaces? If so, how?

Stack Overflow Asked by lo tolmencre on February 7, 2021

Say I have a module like this:

module
├── __init__.py
└── submodule
    ├── B.py
    ├── __init__.py
    └── subsubmodule
        ├── A.py
        └── __init__.py

With the following file contents:

module/submodule/subsubmodule/A.py
    class A:
        pass

module/submodule/subsubmodule/__init__.py
    from .A import A

module/submodule/__init__.py
    from .subsubmodule import A
    from .B import B

module/submodule/B.py
    class B:
        pass

module/__init__.py
    from .submodule import A, B

When I import the module, I want the classes A and B to be available immediately at the top level. That works the way I set it up just fine. But I also end up with submodule in the namespace of module. Why? Is that ok or a problem? It looks unclean to me. Can I avoid this?

In [1]: import module

In [2]: dir(module)
Out[2]: 
['A',
 'B',
 '__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__path__',
 '__spec__',
 'submodule'] # <------------ why is that here? 

I said from .submodule import A, B in the __init__.py of module. I never said from . import submodule. So intermediate modules are dragged into the namespace apparently. Should this be avoided and if so how.

One Answer

I said from .submodule import A, B in the init.py of module. I never said from . import submodule. So intermediate modules are dragged into the namespace apparently. Should this be avoided and if so how.

Nothing is "dragged into the namespace", "submodule" IS a part of "module"s namespace because "submodule" is a part of "module", that is why in the init of module you can do; "from (DOT)submodule ..".

The dot translates to "from THISPACKAGE->submodule ..."

If "submodule" was not part of the "module" package then you wouldn't be able to import it FROM "module" inside module's init.

Answered by Vinzent on February 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP