python - import namespace
Question: If I have a library like:

MyPackage:

  * `__init__.py`

  * SubPackage1

    * `__init__.py`
    * moduleA.py
    * moduleB.py 
  * SubPackage2 
    * `__init__.py`
    * moduleC.py
    * moduleD.py

But I want that users can import moduleA like `import MyPackage.moduleA`
directly. Can I implement this by write some rules in `MyPackage/__init__.py`?


Answer: In `MyPackage/__init__.py`, import the modules you want available from the
subpackages:

    
    
    from __future__ import absolute_import  # Python 3 import behaviour
    
    from .SubPackage1 import moduleA
    from .SubPackage2 import moduleD
    

This makes both `moduleA` and `moduleD` globals in `MyPackage`. You can then
use:

    
    
    from MyPackage import moduleA
    

and that'll bind to the same module, or do

    
    
    import MyPackage
    
    myPackage.moduleA
    

to directly access that module.

However, you _can't_ use

    
    
    from MyPackage.moduleA import somename
    

as that requires `moduleA` to live directly in MyPackage; a global in the
`__init__` won't cut it there.

