Python Namespace and Scope
1. What is a Namespace
A namespace is a container that holds identifiers (variables, functions, objects) and maps them to their corresponding values.
a = 10Here, a resides in a namespace and points to the value 10.
Types of namespaces:
Built-in namespace
Global namespace
Local namespace
2. Built-in Namespace
Contains built-in functions and objects provided by Python.
print(len([1, 2, 3]))
print(type(100))These functions belong to the built-in namespace and are always available.
3. Global Namespace
Created when a module is loaded and remains until the program terminates.
x = 50 # Global variable
def show():
print(x)
show()Global variables are accessible throughout the module.
4. Local Namespace
Created inside a function and destroyed when the function exits.
Local namespace is limited to function scope.
5. Accessing Namespace Using globals()
globals() returns a dictionary of all global identifiers.
6. Accessing Namespace Using locals()
locals() returns a dictionary of local variables within a scope.
7. LEGB Rule (Scope Resolution Order)
Python resolves variable names in the following order:
Local
Enclosing
Global
Built-in
Output follows the closest scope: Local → Enclosing → Global → Built-in.
8. Enclosing Namespace
Occurs in nested functions, holding variables from outer functions.
Inner functions can reference enclosing variables.
9. Modifying Enclosing Variables with nonlocal
nonlocal allows modification of variables in the enclosing namespace.
10. Namespace Lifecycle Demonstration
Shows that separate namespaces prevent conflicts between global and local variables.
Summary
Namespace
Container mapping names to objects
Scope
Region where a variable is accessible
LEGB Rule
Determines variable resolution order
globals()
Access global variables
locals()
Access local variables
Last updated