Python nonlocal keyword is used to instruct the interpreter that the variable you are referring to is in an enclosing scope.
It allows you to declare that a variable is not local to the innermost function and should instead refer to the variable in the nearest enclosing scope.
In other words, it enables us to access and modify variables from the outer function within the inner function.
To use nonlocal, here is the syntax:
nonlocal variable_name
Let’s illustrate the usage of the nonlocal keyword with a few examples:
Example 1: Modifying a variable in the outer function
def outer_function(): x = 10 def inner_function(): nonlocal x x += 5 print(x) inner_function() outer_function() # Output: 15
In this example, the nonlocal keyword is used to access and modify the variable x from the outer function within the inner function.
Without using nonlocal, the inner function would create a new local variable x instead.
Example 2: Using nonlocal with nested functions
def outer_function(): x = 10 def inner_function(): def nested_function(): nonlocal x x += 5 print(x) nested_function() inner_function() outer_function() # Output: 15
In this example, we have a nested function nested_function() within inner_function().
The nonlocal keyword allows you to access the variable x from the outermost function outer_function() and modify its value.
Global vs nonlocal keyword
The nonlocal keyword is often confused with the global keyword.
While both keywords deal with scope, they serve different purposes:
- nonlocal is used to access variables from the nearest enclosing scope, typically in nested functions.
- global is used to declare that a variable is global, making it accessible from anywhere within the program.
Conclusion
The nonlocal keyword in Python provides a way to access and modify variables from the nearest enclosing scope within nested functions.
It allows you to work with variables that are not local to the innermost function.
Understanding the nuances of scope and these keywords can greatly enhance your ability to write clean and efficient code.