10. Scope & Namespaces
Master variable resolution & symbol isolation: `Local scope`, `Enclosing scope`, `Global scope`, `Built-in scope`, the `LEGB rule`, scope modifiers (`global` & `nonlocal`), and runtime namespace inspection (`locals()` & `globals()`).
🎓 Junior Python Curriculum — Select Module
10. Python Scope, Namespaces & LEGB Resolution Rule
1️⃣ The LEGB Resolution Pyramid
When Python encounters a variable name, it searches through four distinct scope levels in strict order:
[E]nclosing Scope --> Inside outer enclosing functions (closures)
[G]lobal Scope --> Top-level module file
[B]uilt-in Scope --> Built-in Python keywords & functions
2️⃣ Local Scope (`L`)
Variables assigned inside a function belong exclusively to that function's local scope. They are created when the function is invoked and destroyed upon return.
rate = 0.2 # 'rate' is Local to calculate_tax
return amount * rate
3️⃣ Enclosing Scope (`E`) & `nonlocal` Keyword
Enclosing scope exists in nested functions. To modify an outer function's variable from an inner function, use the nonlocal keyword.
count = 0 # Enclosing variable
def increment():
nonlocal count
count += 1
return count
return increment
4️⃣ Global Scope (`G`) & `global` Keyword
Global variables are declared at module file level. To modify a global variable inside a function body, you must declare it using global.
def set_ready():
global app_status
app_status = "READY"
5️⃣ Python Namespaces (`locals()` & `globals()`)
A Namespace is a dictionary mapping variable names (keys) to objects (values). You can inspect runtime namespaces using built-in functions:
print(globals()) # Dictionary of module-level global bindings