Middle
What is nonlocal in Python?
sobes.tech AI
Answer from AI
In Python, the keyword nonlocal is used inside nested functions to indicate that a variable refers to the nearest enclosing scope, but not the global scope. This allows modifying a variable from an outer function within an inner function.
Example:
def outer():
x = 5
def inner():
nonlocal x
x = 10
inner()
return x
print(outer()) # Outputs 10
Without nonlocal, attempting to assign a value to x inside inner would create a new local variable, not changing x from outer.