Python nonlocal Keyword
Python nonlocal keyword is used to make the variable which refers to the variable bounded in the nearest scope. Scope to which variable it bound should not be global or local scope. In Python nonlocal variable follows different behavior from identical binding, It searches for variables in another scope. The nonlocal variable is used in the nested function. nonlocal variable is used in declaring the variable.
Advantages of nonlocal:
- It helps in accessing the variable which is not in the same scope.
- Since it makes a variable refer to another variable, it makes the variable more reusable and saves the memory for the new variable.
Disadvantages of nonlocal:
- nonlocal variable is not used with the global and local variable.
- nonlocal variable is not used for a variable which is not in nesting scope.
Demonstrating nonlocal variable:
Example 1: In this example, we demonstrate the working of nonlocal variables. We create the nonlcoal variable and change the content of it in nested scope, and affect the content of the variable in the upper scope.
Example 2: In this example, we see what happens when we make a nonlocal variable to refer to the global variable.
SyntaxError: no binding for nonlocal 'geek_name' found
The possible application for the nonlocal variable is when accessing the variable of another scope without making a new variable it refers to a variable which is recently bounded to it. There is much possible application of nonlocal keywords.
Example 3: In this example, we will see which variable nonlocal refer when we have multiple nested functions and they all have a variable with the same name.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course