nonlocal
Keywordnonlocal
In Python, the nonlocal
keyword is used within a nested function to refer to a variable in the enclosing (non-global) scope. This keyword allows you to modify variables that are defined in the nearest enclosing scope that is not global. It’s particularly useful in cases where you need to update a variable from an outer function within a nested function, without creating a new local variable.
nonlocal
KeywordThe nonlocal
keyword is employed to work with variables in nested functions. Here’s what it accomplishes:
nonlocal
, any assignment to a variable in a nested function would create a new local variable, not modify the outer one.nonlocal
In this example, nonlocal count
in the inner
function refers to the count
variable defined in outer
. It allows the inner
function to modify the count
variable in outer
.
Closures often use nonlocal
to maintain state across multiple calls.
Here, counter
is a closure that retains the state of count
across multiple invocations. The nonlocal
keyword ensures that each call to counter
updates the same count
variable.
nonlocal
helps you achieve this.nonlocal
is useful for creating function closures that maintain state across multiple function calls.The nonlocal
keyword is a powerful feature in Python that enables nested functions to modify variables in their enclosing scopes. It is essential for maintaining state in closures and for modifying variables in outer scopes without creating new local variables. Understanding and using nonlocal
appropriately can lead to more flexible and maintainable code.