Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define namespace in python?

Tags:

python

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

like image 676
john smith Avatar asked Sep 28 '16 09:09

john smith


1 Answers

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.

like image 77
kfb Avatar answered Oct 02 '22 09:10

kfb