Python nonlocal Keyword

02 May, 2022
Python nonlocal keyword is used to reference a variable in the nearest scope. The nonlocal keyword won’t work on local or global variables and therefore must be used to reference variables in another scopes except the global and local one. The nonlocal keyword is used in nested functions to reference a variable in the parent function. 
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.
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 demonstrate the working of the nonlocal keyword.
Python3
def foo():    name = "geek" # Our local variable     def bar():        nonlocal name          # Reference name in the upper scope        name = 'GeekForGeeks' # Overwrite this variable        print(name)             # Calling inner function    bar()         # Printing local variable    print(name) foo()
GeekForGeeks
GeekForGeeks
Example 2: In this example, we see what happens when we make a nonlocal variable to refer to the global variable.
Python3
# Declaring a global variableglobal_name = 'geekforgeeks'  def foo():       # Defining inner function    def bar():               # Declaring nonlocal variable        nonlocal global_name        # Try to reference global variable        global_name = 'GeekForGeeks'# Try to overwrite it        print(global_name)             # Calling inner function    bar()     foo()
Output:
SyntaxError: no binding for nonlocal 'name' found
Example 3: 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():     # Local variable of foo()    name = "geek"     # First inner function    def bar():        name = "Geek"         # Second inner function        def ack():            nonlocal name # Reference to the next upper variable with this name            print(name)   # Print the value of the referenced variable            name = 'GEEK' # Overwrite the referenced variable            print(name)         ack() # Calling second inner function         bar() # Calling first inner function    print(name) # Printing local variable of bar() foo()
Geek
GEEK
geek
Example 4: In this example we will build a reuseable counter (Just for demonstration purpose)
Python3
# Our counter functiondef counter():  c = 0 # Local counter variable     # This function manipulate the local c variable, when called  def count():    nonlocal c    c += 1    return c     # Return the count() function to manipulate the local c variable on every call  return count # Assign the result of counter() to a variable which we use to count upmy_counter = counter()for i in range(3):  print(my_counter())print('End of my_counter')   # Create a new counternew_counter = counter()for i in range(3):  print(new_counter())print('End of new_counter')
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.
clintra
adnanirshad158
ghostixmusic
sweetyty
Blogathon-2021
Picked
python-basics
Blogathon
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.