global and nonlocal Keywords & Variable Binding
1Concept
`global` binds a variable inside a function to the module-level namespace. `nonlocal` binds to the nearest enclosing non-global scope, enabling stateful closures without object orientation.
2Architecture Diagram
def outer():
count = 0
def inner():
nonlocal count ---> Mutates count in enclosing frame!
count += 13Code Example
Python 3.12
def make_counter(initial: int = 0):
count = initial
def increment(step: int = 1) -> int:
nonlocal count
count += step
return count
return increment
counter = make_counter(10)
print(f"Counter Step 1: {counter(5)}")
print(f"Counter Step 2: {counter(2)}")4Expected Output
Counter Step 1: 15 Counter Step 2: 17
5Key Takeaways
- ✓`nonlocal` cannot be used at module level; it requires an enclosing function scope.
- ✓`global` makes code difficult to test and maintain; avoid in concurrent systems.
- ✓Closures with `nonlocal` provide lightweight encapsulation alternative to single-method classes.