10

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).

john smith
  • 235
  • 2
  • 10
  • possible duplicate of http://stackoverflow.com/questions/3913217/what-are-python-namespaces-all-about – deepbrook Sep 28 '16 at 09:52
  • 1
    @j4ck So which answer to that question has already answer my question? – john smith Sep 28 '16 at 09:54
  • 2
    The first one. Name spaces are nothing you can explicitly `define`. They're given by the scope you're coding in. – deepbrook Sep 28 '16 at 09:55
  • For example, if you define a variable within a function definition, that variable is within the scope and namespace of this function only, meaning other functions or parts of code cannot see it. – deepbrook Sep 28 '16 at 09:56
  • Maybe [this](https://bytebaker.com/2008/07/30/python-namespaces/) might help to shed some more light ? – deepbrook Sep 28 '16 at 09:59

1 Answers1

6

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:

my_code/
    module_a/
        __init__.py
        a.py
        b.py
    module_b/
        __init__.py
        a.py
        b.py
    __init__.py
    main.py

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

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

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

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

from module_a.a import *

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

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

from module_a.a import fn as module_a_fn
from module_b.b import fn as module_b_fn

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

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

I hope that helps elucidate the usage a bit more.

kfb
  • 6,252
  • 6
  • 40
  • 51
  • 5
    This answer doesn't consider Classes, NamedTuples, or other things that define scope and are therefore namespaces. – jspencer Dec 27 '18 at 01:44