nonlocal and Mutable State
Modify enclosing scope.
Reading vs writing enclosing variables
An inner function can freely read an enclosing variable, but if it tries to assign to that name, Python treats it as a new local variable instead. This often surprises beginners.
def outer():
count = 0
def inner():
return count
return inner()
print(outer())The assignment trap
Assigning to an enclosing name without declaring intent makes it local, so the outer variable is never updated. Here the change is lost.
def outer():
count = 0
def bump():
count = count + 1
try:
bump()
except UnboundLocalError as e:
print('Error:', e)
outer()All lessons in this course
- First-Class Functions
- Closures and Free Variables
- nonlocal and Mutable State
- Partial Functions