The namespaces in Python is a container that holds identifiers (names of variables, functions, classes, etc.) and maps them to their corresponding objects. It acts as a boundary, ensuring that names are unique and avoiding naming conflicts. Python provides multiple types of namespaces:
- Local Namespace:
The local namespace is created whenever a function is called and is destroyed when the function exits. It contains the names of variables and parameters that are defined within the function. These variables are only accessible within the function’s body. When the function is called again, a new local namespace is created.
def my_function(): local_var = "I'm local to my_function" print(local_var) my_function() # Trying to access local_var outside the function # This will raise a NameError # print(local_var)
2. Enclosing Namespace:
Enclosing namespaces come into play when you have nested functions, where one function is defined inside another. The inner function can access variables from the outer function’s namespace.
def outer_function(): outer_var = "I'm in the outer function" def inner_function(): print(outer_var) # Accessing variable from the enclosing namespace inner_function() outer_function() # Trying to access outer_var outside the function # This will raise a NameError # print(outer_var)
3. Global Namespace:
The global namespace covers the entire module or script. Variables defined at the top level of the module belong to the global namespace and are accessible from anywhere within the module.
global_var = "I'm in the global namespace" def my_function(): print(global_var) # Accessing variable from the global namespace my_function() print(global_var)
4. Built-in Namespace:
The built-in namespace contains Python’s built-in functions and objects. These names are always available without the need for importing or defining them. Examples include functions like print() and objects like int and lists.
# Using a built-in function and object print(len([1, 2, 3])) # Trying to redefine a built-in function # This will raise a SyntaxError # def len(x): # return 42