nonlocal in Python 3
React, Django and SQL developer at Forma.ai
#TIL about nonlocal in Python 3
Inner functions can access outer variables but can’t modify them by default
Here’s a contrived simple example
def outer():
num = 0
def inner():
nonlocal num
num += 1
inner()
If you remove the nonlocal result, you’ll get an UnboundLocalError
UnboundLocalError: cannot access local variable 'result' where it is not associated with a value
Most of the time, it might be a code smell (given the global variable).
Never encountered it until writing messy Leetcode!