Nonlocal in Python
In Python, variables can have different levels of scope. When a variable is defined inside a function, it is said to have local scope. This means that the variable can only be accessed from within the function where it is defined.
Sometimes, however, you may need to access a variable from within a nested function that is defined inside the original function. In this case, you can use the `nonlocal` keyword to indicate that you want to use the variable from the enclosing (non-global) scope.
Here's an example:
def outer_function():
x = 10
def inner_function():
nonlocal x
x = 20
print("x inside inner_function:", x)
inner_function()
print("x inside outer_function:", x)
outer_function()
In the above code, the variable
x
is defined inside the function
outer_function()
. We then define a nested function called
inner_function()
, which attempts to modify the value of
x
.
Since
x
is not defined inside
inner_function()
, we need to use the `nonlocal` keyword to indicate that we want to use the value of
x
from the enclosing (non-global) scope. We then set the value of
x
to 20, and print its value.
When we call
outer_function()
, the output will be:
x inside inner_function: 20
x inside outer_function: 20
As you can see, the value of
x
was successfully modified by
inner_function()
, and the modified value was retained even after the function returned.
The `nonlocal` keyword is useful when you need to modify a variable from within a nested function, but you don't want to define the variable in the global scope.
It's important to note that the `nonlocal` keyword only works for variables in an enclosing (non-global) scope. If you need to modify a variable in the global scope, you can use the `global` keyword instead.