What does the nonlocal python keyword do in Python 3.x?
To close debugging questions where the OP needs nonlocal and doesn’t realize it, please use “Is it possible to modify a variable in Python that is in the outer scope, but not global?” instead.
Although Python 2 is officially unsupported as of January 1, 2020, if for some reason you are forced to maintain a Python 2.x codebase and need an equivalent to nonlocal, see the nonlocal keyword in Python 2.x.
The nonlocal
keyword in Python is a way to modify variables in the nearest enclosing scope that isn’t global. It becomes particularly useful when working with nested functions and you need to modify a variable from an outer function’s scope.
def outer_function():
x = 10
def inner_function():
nonlocal x # Accesses x from the outer scope
x = 20
inner_function()
print(x) # Output will be 20
outer_function()
In this example, nonlocal python
helps ensure that the variable x
from the outer scope is modified, rather than creating a new local variable within the inner function."
I’ve found nonlocal python
most helpful in cases involving nested functions. When a variable exists in an enclosing scope (but isn’t global), nonlocal
ensures you can modify it within an inner function. Here’s an example:
def outer():
count = 0
def increment():
nonlocal count # Modify count in the enclosing scope
count += 1
increment()
increment()
print(count) # Output will be 2
outer()
In this code, nonlocal count
lets the increment
function update count
directly in the outer function. Without nonlocal
, count
would be treated as a new local variable, and the changes wouldn’t persist outside the inner function.
Without nonlocal python
, modifying variables in outer (non-global) scopes can be tricky. If you try assigning a new value to a variable from an outer scope without nonlocal
, Python will treat it as a new local variable within the inner function:
def outer():
x = 5
def inner():
x = 10 # Creates a new local variable instead of modifying the outer 'x'
inner()
print(x) # Output will still be 5
outer()
In this case, x
in the inner function is independent of x
in the outer function. Using nonlocal python
allows you to directly modify the outer x
, ensuring changes are reflected in the enclosing scope. It’s a cleaner alternative to using global variables, avoiding unintended side effects.