In Python, the namespace is used to provide a unique name to each object. Python dictionary is used to maintain the namespace. Dictionaries play an important role in declaring and representing namespace. Here, the name defines the unique name and space defines the scope or location. In Python, namespaces are used to organize objects in the application program. There are three types of namespace exists in python.
dir(__builtins__)
var initial = 0 # the namespace created for this variable is global namespace
def outer(): # the namespace is created for this function is enclosing namespace
print("This is an outer function")
def inner() # the namespace is created for this function is a local namespace
print("This is an inner function")
return
inner()
return
outer()
Scope or location defines the memory region where the specific programming application is created. The scope of an individual application program is separated using an internal program and one application cannot interrupt another. The order of searching or scope of the namespace is:
This is usually known as LEGB rule. Here, L denotes Local, E denotes Enclosing, G donates Global, and B denotes Built-in respectively.
The scope of variables plays an important role to set the lifetime of the namespace. The lifetime of a namespace exists until the scope of the variable comes to an end. An outer namespace cannot access the object of the inner namespace. Multiple namespaces have the same object name but it does not create any ambiguity. As the object names are separated by their respective namespaces.
Dictionaries are used to implement namespaces in Python. There are two in-built functions available to access namespace dictionaries. One is globals()
function and another one is locals()
function. But built-in namespace does not use a dictionary, it is implemented by using the Python module.
globals()
function: This function is used to return the instance or reference of currently executing a global namespace dictionary. In global namespace, this instance is used to access the object. It differs in looking base on the version of the operating system and Python version that is installed in the system. locals()
function: This function is used to provide different types of built-in functions. These functions are called only in the local namespace. This locals()
function provides the namespace dictionary in the local namespace. The function parameters are also used in the local namespace. Sometimes, locals()
function behaves like a globals()
function when locals()
are declared outside of a function but inside the main program.