We all know that python is an easy programming language for beginners because of its simple syntax, and how easily we can perform tasks using its functions. But what we ignore is that python does have some hidden concepts which are very important for good coding practices.
Ever heard of nonlocal variables? In this article, we will learn about the nonlocal keyword in Python, its purpose, and how it is different than other global variables.
But first, let's start with recalling some basics of python like variables, keywords, and their importance, and further diving into today's topic.
What are Variables?
Variables in Python are a reserved memory location to store values or we can say it is a name given to a memory location. Whereas keywords in python are the reserved words that have a special meaning to the interpreter. These words cannot be used as a variable.
These keywords can be used with variables to create special variables with specific functionalities and scope in our program. For example, the most common types of variables are Global variables and local variables. Here, global and local are keywords used with any variable to decide their scope.
- Global Variable: They are declared outside the function or in a global scope and can be accessed anywhere in the program i.e. both inside of functions and outside.
- Local Variable: They are declared inside the function’s body or in a local scope and local variables can be accessed only inside the function where defined but never outside it. If called outside it returns Namerror which states that the variable is not defined.
What is nonlocal keyword in Python?
After global and local variables, we have Non-local variables where non-local means “neither local nor global”. The nonlocal is a keyword in python that is used to declare any variable as not local but instead comes from the nearest enclosing scope that is not global.
This keyword doesn’t work on global and local variables hence, therefore used to reference a variable in the nearest scope except for the local and global scope i.e value from the nearest enclosing block is taken. It works with variables inside nested functions, to reference a variable in the parent function.
So, in short it lies in between the global and local scope.
What is the purpose of a nonlocal keyword?
Let us understand the concept of nonlocal more clearly using some examples. Below is an example of global and local variables.
def outer(): global string string = "Favtutor" def inner(): string= "Python Favtutor Classes" # Overwriting value of a variable string print("inner function:", string) inner() print("outer function:", string) outer()
inner function: Python Favtutor Classes outer function: Favtutor
In this example, as we can see that we have declared the “string” variable as a global variable with the value “Favtutor” and then inside an inner() function we tried to overwrite the value of a variable to “Python Favtutor classes”. While printing the variable once inside the function and then outside the function we observed different outputs.
This is because though the variable name is the same as “string” the variable scope is different each time when we declared it inside the function we didn’t mention scope so by default python has taken it as a local variable inside a function and for the outer function we manually declared it as global so it has global scope.
As a result of which, when we printed the value of the inner() function variable we got “Python Favtutor classes” because of its local scope but outside in outer() function the value of a local variable is not accessible so it returns the global value of it which can be accessed anywhere.
Now let us assume we want the outer() function to access local scope value only, what we can do here to achieve this is use the Non-local keyword for our variable “string” as below.
def outer(): string = "Favtutor" # Local Variable def inner(): nonlocal string #declaring a non local variable string= "Python Favtutor Classes" # Overwriting value of a variable string print("inner function:", string) inner() print("outer function:", string) outer()
inner function: Python Favtutor Classes outer function: Python Favtutor Classes
As we can see the inner() function is actually a nested function inside the outer() function. By default variable scope is declared by where it is initialized in a program. As we specified it is nonlocal which means it can be accessed by its parent function its scope is beyond local and that’s the reason behind the outer() function printing the overwriting value of the “string” variable.
The enclosing scopes of inner functions are called nonlocal scopes and we use the nonlocal keyword to modify the variable scope to nonlocal that is neither local nor global. Nonlocal keywords bind one or more variables to the outer scope i.e. to the parent function.
Pros of using nonlocal
- Accessing the variable in the upper scope is made easier by it.
- Reusing the referenced variable also means reusing the variable's memory address, which conserves memory.
Cons of using nonlocal
- Neither global nor local variables may be referred to using the nonlocal keyword.
- Only nested structures may be utilized using the nonlocal keyword.
What is the difference between nonlocal and global?
The main difference is that Global is used to access and modify global variables from within a function, while nonlocal is used to access and modify variables from the nearest enclosing scope that is not global.
Nonlocal declarations in a local scope do not require the variable to be pre-bound, which is another fundamental distinction between them. These variables must already have been bound in the surrounding namespace to avoid syntax errors.
While a nonlocal statement allows for the alteration of an enclosing scope variable in the local scope, a global statement allows for the modification of a global variable in the local scope. Nonlocal variables must already exist, although global variables can be declared with brand-new variables.
So, now we understood Python's nonlocal keyword with an example, what are some of its advantages and how it is different from than global scope in this programming language.