A namespace in Python is a system that ensures all the names in a program are unique and can be used without any conflicts. Think of it as a dictionary where the keys are the names of variables, functions, and classes, and the values are the objects themselves. Each namespace is a separate, isolated container for names.
The primary use case for namespaces is to prevent naming collisions. You can have a variable named x in one function and another variable named x in a different function, and they won't interfere with each other because they exist in different namespaces.
1. Types of Namespaces
Python maintains several namespaces, and it searches them in a specific order to find the object you're referring to.
a) Local Namespace
This namespace is created whenever a function is called. It contains all the names (variables, parameters) that are defined inside that function. It is temporary and is deleted once the function finishes its execution.
- Use Case: To store variables that are only needed for a function's specific task, keeping them isolated from the rest of the program.
Python
# --- Local Namespace Example ---
def my_function():
# 'x' and 'message' exist only in the local namespace of this function.
x = 10
message = "Hello from the function"
print(f"Inside the function, x is: {x}")
my_function()
# The following line would cause a NameError because 'x' is not in the global namespace.
# print(x)
b) Global Namespace
This namespace is created for each module (each .py file) when it is imported or run. It contains all the names defined at the main level of your script, including global variables and functions.
- Use Case: To define functions and variables that need to be accessible throughout your entire script.
Python
# --- Global Namespace Example ---
# 'global_var' is defined in the global namespace of this script.
global_var = 100
def another_function():
# This function can READ the global variable.
print(f"Inside the function, we can access the global variable: {global_var}")
another_function()
print(f"Outside the function, the global variable is: {global_var}")
c) Built-in Namespace
This namespace is created when the Python interpreter starts up. It contains all of Python's built-in functions and exceptions, like print(), len(), str(), and ValueError. These names are always available in any module.
- Use Case: Provides the fundamental functions and types that are always available without needing to import anything.
Python
# --- Built-in Namespace Example ---
# 'print' and 'len' are part of the built-in namespace.
print("This is a built-in function.")
print(f"The length of this string is: {len('this string')}")
2. The LEGB Rule (Scope Resolution)
When you use a variable name, Python has a specific order in which it searches the namespaces to find that name. This is known as the LEGB rule:
1. Local: The innermost scope, containing local names inside the current function.
2. Enclosing: The scope of any enclosing functions (used with nested functions).
3. Global: The scope of the current module.
4. Built-in: The outermost scope, containing Python's built-in names.
Python stops at the first namespace where it finds the name.
Python
# --- LEGB Rule Example ---
x = "I am global" # G: Global scope
def outer_function():
x = "I am enclosing" # E: Enclosing scope
def inner_function():
x = "I am local" # L: Local scope
print(f"Inside inner_function: {x}") # Python finds 'x' in the Local scope first.
inner_function()
print(f"Inside outer_function: {x}") # Python finds 'x' in the Enclosing scope.
outer_function()
print(f"In the main script: {x}") # Python finds 'x' in the Global scope.
3. Functions for Interacting with Namespaces
You can directly inspect the global and local namespaces using built-in functions. There are no special "methods" or "operators" for namespaces themselves; interaction is done through these functions and Python's automatic name lookup.
globals()
The globals() function returns a dictionary representing the current global namespace.
- Use Case: For introspection and debugging, to see all the global variables and functions that are currently defined.
Python
# --- globals() Example ---
global_variable = 50
def some_function():
pass
# The globals() dictionary contains everything defined at the module level.
global_namespace = globals()
print("\n--- A snippet from the global namespace ---")
print(f"global_variable: {global_namespace['global_variable']}")
print(f"some_function object: {global_namespace['some_function']}")
locals()
The locals() function returns a dictionary representing the current local namespace. When called inside a function, it shows you the names available within that function.
- Use Case: Primarily for debugging, to inspect the state of local variables at a certain point inside a function.
Python
# --- locals() Example ---
def another_function(param1, param2):
local_var = "test"
# The locals() dictionary contains all names defined within this function call.
print("\n--- The local namespace for this function call ---")
print(locals())
another_function(10, "hello")