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.
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.
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.
Geek GEEK geek
Example 3: In this example, we will build a reusable counter (Just for demonstration purpose
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.