Python namespace change of `import package.sub_module; from package import *`
<p>The <a href="https://docs.python.org/3/tutorial/modules.html#importing-from-a-package" rel="nofollow">Python documentation</a> says</p>

<blockquote>
  <p>Consider this code:</p>
</blockquote>

<pre><code>import sound.effects.echo
import sound.effects.surround
from sound.effects import *
</code></pre>

<blockquote>
  <p>In this example, the echo and surround modules are imported in the
  current namespace because they are defined in the sound.effects
  package when the from...import statement is executed. <strong>(This also works
  when __all__ is defined.)</strong></p>
</blockquote>

<p>I try the following code</p>

<pre><code># package/
#     __init__.py
#     sub_module.py

import package.sub_module
from package import *
print(sub_module)
</code></pre>

<p>When <code>package/__init__.py</code> is empty, the code works fine. However, when <code>package/__init__.py</code> contains <code>__all__ = []</code>, <code>print(sub_module)</code> will raise <code>NameError</code>.
What is <em>(This also works when <strong>all</strong> is defined.)</em> from the documentation means?</p>

<hr>

<p>The codes:</p>

<pre><code>package/
    __init__.py
    sub_module.py # empty file
main.py
</code></pre>

<p>In main.py:</p>

<pre><code>import package.sub_module
from package import *
print(sub_module)
</code></pre>

<p>When <code>package/__init__.py</code> is empty, executing <code>python3 main.py</code> gets 
    <code>&lt;module 'package.sub_module' from '/path/to/package/sub_module.py'</code></p>

<p>When <code>package/__init__.py</code> contains <code>__all__ = []</code>, executing <code>python3 main.py</code> gets</p>

<pre><code>Traceback (most recent call last):
File "main.py", line 3, in &lt;module&gt;
    print(sub_module)
NameError: name 'sub_module' is not defined
</code></pre>

<p>If you define <code>__all__</code>, then <em>only</em> the attributes mentioned there will be imported via <code>*</code>, while the excluded ones have to be imported <em>explicitly</em>. So either use</p>

<pre><code>from package import submodule
</code></pre>

<p>or if you <em>really</em> want to use the (discouraged!) <code>from package import *</code>, declare</p>

<pre><code>__all__ = ['submodule']
</code></pre>

<p>in <code>package</code>. Note how tedious it will become to keep this up-to-date...</p>

python