python - import namespace
<p>If I have a library like:</p>

<p>MyPackage:</p>

<ul>
<li><p><code>__init__.py</code></p></li>
<li><p>SubPackage1</p>

<ul>
<li><code>__init__.py</code></li>
<li>moduleA.py</li>
<li>moduleB.py </li>
</ul></li>
<li>SubPackage2

<ul>
<li><code>__init__.py</code></li>
<li>moduleC.py</li>
<li>moduleD.py</li>
</ul></li>
</ul>

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

<p>In <code>MyPackage/__init__.py</code>, import the modules you want available from the subpackages:</p>

<pre><code>from __future__ import absolute_import  # Python 3 import behaviour

from .SubPackage1 import moduleA
from .SubPackage2 import moduleD
</code></pre>

<p>This makes both <code>moduleA</code> and <code>moduleD</code> globals in <code>MyPackage</code>. You can then use:</p>

<pre><code>from MyPackage import moduleA
</code></pre>

<p>and that'll bind to the same module, or do</p>

<pre><code>import MyPackage

myPackage.moduleA
</code></pre>

<p>to directly access that module.</p>

<p>However, you <em>can't</em> use</p>

<pre><code>from MyPackage.moduleA import somename
</code></pre>

<p>as that requires <code>moduleA</code> to live directly in MyPackage; a global in the <code>__init__</code> won't cut it there.</p>

python import namespaces package