How to define namespace in python?
<p>It seems that python do have namespaces. But All I can get is people telling me what namespace or scope is. So how do you define a namespace in python? All I need is the syntax (and with an example would be much better). </p>

<p>A "namespace" in Python is defined more by the layout of the code on disk than it is with any particular syntax. Given a directory structure of:</p>

<pre><code>my_code/
    module_a/
        __init__.py
        a.py
        b.py
    module_b/
        __init__.py
        a.py
        b.py
    __init__.py
    main.py
</code></pre>

<p>and assuming each <code>a.py</code> and <code>b.py</code> file contains a function, <code>fn()</code>, the import syntax to resolve the namespace works like so (from <code>main.py</code>):</p>

<pre><code>from module_a.a import fn  # fn() from module_a/a.py
from module_a.b import fn  # fn() from module_a/b.py
from module_b.a import fn  # fn() from module_b/a.py
from module_b.b import fn  # fn() from module_b/b.py
</code></pre>

<p>At this point, <code>fn()</code> is available within <code>main.py</code> and will call whichever implementation you imported.</p>

<p>It's also possible to use the <code>from module import *</code> syntax, but this is discouraged in favour of being more specific:</p>

<pre><code>from module_a.a import *
</code></pre>

<p>Here, <code>fn()</code> is available within <code>main.py</code>, and also <em>any other symbol defined in <code>module_a/a.py</code></em>.</p>

<p>If we want to have access to both <code>module_a/a.py</code>'s <code>fn()</code> and also the <code>fn()</code> from <code>module_b/b.py</code>, we can do one of two things: either we use the <code>from module import thing as something</code> syntax:</p>

<pre><code>from module_a.a import fn as module_a_fn
from module_b.b import fn as module_b_fn
</code></pre>

<p>and use them in our <code>main.py</code> as <code>module_a_fn()</code> and <code>module_b_fn()</code>, or we can just import the module and reference it directly in the code, so in <code>main.py</code>:</p>

<pre><code>import module_a.a
import module_a.b

module_a.a.fn()  # call fn() from module_a/a.py
module_a_b.fn()  # call fn() from module_a/b.py
</code></pre>

<p>I hope that helps elucidate the usage a bit more.</p>

python