Python nonlocal keyword is used to reference a variable in the nearest scope.
Python nonlocal Keyword Example
In this example, we demonstrate the working of the nonlocal keyword.
Python3
def foo():
name = "geek"
def bar():
nonlocal name
name = 'GeeksForGeeks'
print (name)
bar()
print (name)
foo()
|
Output
GeeksForGeeks
GeeksForGeeks
What is nonlocal keyword in Python
The nonlocal keyword won’t work on local or global variables and therefore must be used to reference variables in another scope except the global and local one. The nonlocal keyword is used in nested functions to reference a variable in the parent function.
Advantages of nonlocal:
- It helps in accessing the variable in the upper scope.
- Since the referenced variable is reused, the memory address of the variable is also reused and therefore it saves memory.
Disadvantages of nonlocal:
- The nonlocal keyword can’t be used to reference global or local variables.
- The nonlocal keyword can only be used inside nested structures.
Example 1: In this example, we see what happens when we make a nonlocal variable to refer to the global variable.
Python3
global_name = 'geeksforgeeks'
def foo():
def bar():
nonlocal global_name
global_name = 'GeeksForGeeks'
print (global_name)
bar()
foo()
|
Output:
SyntaxError: no binding for nonlocal 'name' found
Example 2: In this example, we will see which variable nonlocal refers to when we have multiple nested functions with variables of the same name.
Python3
def foo():
name = "geek"
def bar():
name = "Geek"
def ack():
nonlocal name
print (name)
name = 'GEEK'
print (name)
ack()
bar()
print (name)
foo()
|
Output
Geek
GEEK
geek
Example 3: In this example, we will build a reusable counter (Just for demonstration purpose
Python3
def counter():
c = 0
def count():
nonlocal c
c + = 1
return c
return count
my_counter = counter()
for i in range ( 3 ):
print (my_counter())
print ( 'End of my_counter' )
new_counter = counter()
for i in range ( 3 ):
print (new_counter())
print ( 'End of new_counter' )
|
Output
1
2
3
End of my_counter
1
2
3
End of new_counter
Note: Notice how the local c variable keeps alive on every call of our counter variables.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
14 Dec, 2022
Like Article
Save Article