If a variable is declared in an enclosing (outer) function, it is nonlocal to nested (inner) function.
nonlocal keyword is used to update these variables inside a nested function.
|var1,var2,…||Required||List of identifiers you want to declare nonlocal|
Here’s a basic example that tries to reassign enclosing function’s local variable inside a nested function.
# enclosing function def f1(): x = 42 # nested function def f2(): x = 0 print(x) # x is 0 f2() print(x) # x is still 42 f1()
Here, the value of existing variable
x didn’t change. Because, Python created a new local variable named
x that shadows the variable in the outer scope.
Preventing that behavior is where the nonlocal keyword comes in.
# enclosing function def f1(): x = 42 # nested function def f2(): nonlocal x x = 0 print(x) # x is now 0 f2() print(x) # x remains 0 f1()
x inside the nested function now refers to the
x outside the function, so changing
x inside the function changes the
x outside it.