Python › Functions & Scope
How does the 'nonlocal' keyword let a nested function modify a variable in its ENCLOSING (not global) scope?
IntermediateAnswer
'nonlocal' tells Python that an assignment inside a nested function should modify the variable in the nearest ENCLOSING function's scope (not create a new local, and not reach all the way to global) — essential for implementing stateful closures, like a counter that persists across calls to an inner function.
def make_counter():
count = 0
def increment():
nonlocal count # modifies the ENCLOSING 'count', not global or a new local
count += 1
return count
return increment
counter = make_counter()
print(counter()) # 1
print(counter()) # 2Real-world example Building a stateful closure (like a counter or accumulator) where the inner function needs to persist and modify enclosing state across calls.