Variable Scoping, LEGB Rule & global / nonlocal Keywords
1Concept
Python resolves variables using the LEGB Rule (Local -> Enclosing -> Global -> Built-in). To reassign a variable outside local scope, use global (module-level) or nonlocal (nested enclosing function).
2Architecture Diagram
LEGB Scope Hierarchy:
[L] Local Scope (Inside function)
└──► [E] Enclosing Scope (Outer function closure)
└──► [G] Global Scope (Module file)
└──► [B] Built-in Scope (len, range, print)3Code Example
Stage 0 Language Foundations
counter = 100 # Global
def outer_function():
count = 10 # Enclosing
def inner_function():
nonlocal count # Modify enclosing variable
count += 5
print(f"Inner modified enclosing count: {count}")
inner_function()
print(f"Outer count after inner call: {count}")
outer_function()
print(f"Global counter remains: {counter}")4Expected Output
Inner modified enclosing count: 15 Outer count after inner call: 15 Global counter remains: 100
5Key Takeaways
- ✓Variables declared in if-blocks or loops are NOT block-scoped; they exist at function scope.
- ✓Use nonlocal to modify variables in closure wrappers.
- ✓The LEGB rule searches from innermost to outermost scope.