Wednesday, November 27, 2024
Google search engine
HomeLanguagesPython nonlocal Keyword

Python nonlocal Keyword

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" # Our local variable
 
    def bar():
        nonlocal name          # Reference name in the upper scope
        name = 'GeeksForGeeks' # Overwrite this variable
        print(name)
         
    # Calling inner function
    bar()
     
    # Printing local variable
    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




# Declaring a global variable
global_name = 'neveropen'
 
 
def foo():
   
    # Defining inner function
    def bar():
       
        # Declaring nonlocal variable
        nonlocal global_name        # Try to reference global variable
        global_name = 'GeeksForGeeks'# Try to overwrite it
        print(global_name)
         
    # Calling inner function
    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():
 
    # 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()


Output

Geek
GEEK
geek

Example 3: In this example, we will build a reusable counter (Just for demonstration purpose

Python3




# Our counter function
def 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 up
my_counter = counter()
for i in range(3):
  print(my_counter())
print('End of my_counter')
   
# Create a new 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.

RELATED ARTICLES

Most Popular

Recent Comments