Python - Namespace
Python namespace is a mapping of unique names to objects related to scope.
Namespace vs Scope
- Namespace - A namespace is a mapping that holds the identifiers, such as variables, functions and classes.
- Scope - A Scope is the context in which a variable or function is accessible.
Types of Namespace
- built-in - The Python built-in namespace (
id()
,type()
,__name__
, etc...). - global - The global namespace refers to the namespace of the current module or script.
- local - The local namespace pertains to the namespace within a function or class.
y = 10
def doSomething(x):
z = 32
print(locals()) # {'x': 10, 'z': 32}
return x + y + z
doSomething(10)
print(globals()) # {'__name__': '__main__', ..., 'y': 10, 'doSomething': <function doSomething at 0x000>}
globals() - Get the global namespace dictionary.
locals() - Get the current scope namespace dictionary.