A namespace is a system that organizes names (i.e., identifiers) in a way that they can be assigned to objects and easily accessed during the execution of a program. It helps in avoiding naming conflicts and provides a hierarchical structure for names to be stored and referenced.
Python has different types of namespaces, which include:
Built-in Namespace: It contains all the names of Python's built-in functions, modules, and exceptions. These names are always available without any import statement. For example, print(), len(), range(), etc.
Global Namespace: It represents the names defined at the top level of a module or script. These names can be accessed from anywhere within the module.
Enclosing Namespace: This namespace comes into play when working with nested functions. It contains the names from the nearest enclosing function.
Local Namespace: It includes the names defined within the current function or block. These names are created when a function is called and removed when the function exits.
When a name is accessed, Python searches for it in the following order:
Local Namespace (if the code is inside a function or block)
Enclosing Namespace (if the code is inside a nested function)
Global Namespace (for names defined at the top level of the module)
Built-in Namespace
If a name is found in any of these namespaces, Python retrieves its value. If not found, it raises a NameError.
Example:
# Global Namespace
global_var = 10
def my_function():
# Local Namespace
local_var = 20
print(global_var) # Accessing global_var from the Global Namespace
def nested_function():
# Enclosing Namespace
enclosing_var = 30
print(local_var) # Accessing local_var from the Local Namespace
nested_function()
my_function()
In this example, global_var is defined in the Global Namespace and is accessible within the function my_function. local_var is defined in the Local Namespace of my_function and is accessible within the function and its nested function nested_function.