What is the nonlocal keyword in Python?
In this shot, we will discuss the nonlocal keyword in Python.
Variables in Python are mainly of 2 types:
-
Global variables: Declared outside the function or in a global scope.
-
Local variables: Declared inside the function’s body or in a local scope.
The nonlocal keyword is used to work with variables inside nested functions whose local scopes are not defined.
In other words, when we declare a variable as nonlocal, it means it is neither local nor global.
Suppose we have a nested function, as shown in the code snippet below.
# First Functiondef f():x = 10# Nested Functiondef g():x = 1g()print (x)f()
Expected output
Although we expect the output to be 1, that is not the case. The actual output here will be 10.
Explanation
x = 10 and x = 1 have different IDs, meaning that they are stored as different objects. So, when we call the f() function, the local variable x (which is equal to 10) is returned.
Now, if we want to get x = 1 as the output, we need to add the nonlocal keyword inside the nested function, as shown below.
# First Functiondef f():x = 10# Nested Functiondef g():nonlocal xx = 1g()print (x)f()
Explanation
-
In line 2, we initiate our first function.
-
In line 3, we declare a local variable
x = 10. -
In line 6, we declare a nested function.
-
In line 7, we assign the
nonlocalkeyword tox, as a result of which any defined values ofxwill now be taken in subsequent entries and the result will be the newx. -
In line 8, we assign a value of 1 to
x. -
In line 9, we call the
g()function, which now carriesx = 1along with it. -
In line 10, we print the value of
x, which comes out to be 1. -
In line 12, we call the
f()function so that the entire function gets executed.