What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Python nonlocal Keyword (Nonlocal vs Global scope)

  • Dec 01, 2023
  • 6 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Komal Gupta
Python nonlocal Keyword (Nonlocal vs Global scope)

In Python, variables can be categorized into two types: global variables and local variables. Global variables are declared outside of a function, making them accessible throughout the program. On the other hand, local variables are declared within the function's body and are only accessible within that specific function. But what happens when we have nested functions and need to work with variables that are not strictly local or global? This is where the nonlocal keyword comes into play. In this article, we will learn about the nonlocal keyword in Python, its purpose, and how it is different than other global variables.

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.

 

python variable scopes

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()

 

Output:

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()

 

Output:

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

  1. Accessing the variable in the upper scope is made easier by it.
  2. Reusing the referenced variable also means reusing the variable's memory address, which conserves memory.

Cons of using nonlocal

  1. Neither global nor local variables may be referred to using the nonlocal keyword.
  2. Only nested structures may be utilized using the nonlocal keyword.

Let's now move forward to understand the usage of nonlocal keyword with the help of examples.

Usage of the Nonlocal Keyword

The nonlocal keyword allows us to access and modify variables in the immediate outer scope of a nested function. This is particularly useful when we want to update a variable's value within the nested function without affecting its value in the global scope or other nested functions.

Let's explore some examples to see the nonlocal keyword in action.

Example 1: Updating a Nonlocal Variable

Consider the following code:

def outer_function():
    x = "outer"

    def inner_function():
        nonlocal x
        x = "inner"

    inner_function()
    print("Value of x:", x)

outer_function()

 

Output:

Value of x: inner

 

In this example, we have an outer function that declares a variable x and a nested inner function. Inside the inner function, we use the nonlocal keyword to indicate that we want to modify the x variable from the outer function's scope. By assigning a new value to x within the inner function, we update its value in the outer function as well.

Example 2: Nonlocal Variables in Multiple Nested Functions

Now, let's consider a scenario where we have multiple levels of nested functions, each with its own variable named x.

def outer_function():
    x = "outer"

    def inner_function_1():
        x = "inner 1"

        def inner_function_2():
            nonlocal x
            x = "inner 2"

        inner_function_2()
        print("Value of x in inner_function_1:", x)

    inner_function_1()
    print("Value of x in outer_function:", x)

outer_function()

 

Output:

Value of x in inner_function_1: inner 2
Value of x in outer_function: outer

 

In this example, we have three levels of nested functions: outer_function, inner_function_1, and inner_function_2. Each level has its own variable named x. By using the nonlocal keyword within inner_function_2, we can update the value of x in inner_function_1.

 

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.

Conclusion

The nonlocal keyword in Python enables us to work with variables within nested functions where the variables' local scopes are not defined. It provides a way to access and modify variables in the immediate outer scope of a nested function. 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.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Komal Gupta
I am a driven and ambitious individual who is passionate about programming and technology. I have experience in Java, Python, and machine learning, and I am constantly seeking to improve and expand my knowledge in these areas. I am an AI/ML researcher. I enjoy sharing my technical knowledge as a content writer to help the community.