In Python, a variable defined in a nested function is local to that function by default, which means it cannot be accessed or modified from the outer function or global scope. However, using the nonlocal keyword, you can modify the value of a variable defined in the outer function from the nested function.
Here's an example:
def outer_function(): x = 0 def inner_function(): nonlocal x x += 1 return x return inner_functionfunc = outer_function()print(func()) # Output: 1print(func()) # Output: 2 |
In this example, outer_function defines a variable x and returns a nested function inner_function. inner_function increments the value of x using the nonlocal keyword, which allows it to modify the value of x defined in the outer function.
When outer_function is called, it returns inner_function. This returned function is assigned to the variable func. We can then call func multiple times, and it will increment and return the value of x each time.
Using nonlocal can be useful when you need to modify a variable defined in the outer function from the nested function. However, it should be used with caution, as it can make the code harder to understand and maintain.