Python Nonlocal Methods Made Simple with Examples

What is a nonlocal keyword in Python?

The Python nonlocal keyword doesn’t work on local variables or global variables, it can be used to refer to variables in a scope other than local and global.

Most of the time, the nonlocal keyword is used in nested functions, where it can point to a variable that was set in the function above it.

Additional information from w3school, the nonlocal keyword works with variables inside nested functions, where the variable should not belong to the inner function.

Demonstrating nonlocal variables in Python

In this demonstration, let us understand how the nonlocal works in Python.

We’ll look at a few examples of Python nonlocal methods. In Python, it is possible to define a function inside the function.

Example:

def outer_func():
    print('This is the outer function')

    def inner_func():
        print('This is the inner function')

    inner_func()


outer_func()

Output:

This is the outer function
This is the inner function

In the example, we have a function called outer_func that contains another function called inner_func.

This nesting ensures they are not global.

The inner_func can access the enclosing scope of outer_func, known as its “enclosing scope.”

When a variable is neither local nor global to inner_func, it’s called the “nonlocal scope.”

Let’s modify the outer_func and the inner_func from the example above:

def outer_func():
    str_msg = 'This is the outer function'
    print(str_msg)

    def inner_func():
        print(str_msg)

    inner_func()


outer_func()

Output:

This is the outer function
This is the outer function

When the outer_func function is called, Python reads the inner_func function and executes it.

After Python executes the inner_func function, it will look for the str_msg variable in the local scope of the inner_func.

If it doesn’t find the str_msg variable in the local scope, Python will start to look in the enclosing scope, which is the scope of the outer_func function.

Another example:

str_msg = 'This is the global scope'


def outer_func():

    def inner_func():
        print(str_msg)

    inner_func()


outer_func()

Output:

This is the global scope

In the example given above, Python searches for the str_msg variable in the local scope of the inner_func function.

Since Python can’t find the variable, it looks for it in the outer_func function’s enclosing scope.

And if Python still can’t find the str_msg variable in the scope of the outer_func function, it will move up to the global scope.

Using the nonlocal variable.

def outer_func():
    str_msg = 'This is the outer scope'
    print(str_msg)

    def inner_func():
        nonlocal str_msg
        str_msg = 'This is the inner scope'
        print(str_msg)

    inner_func()
    print(str_msg)


outer_func()

Output:

This is the outer scope
This is the inner scope
This is the inner scope

In the above example, the nonlocal keyword tells Python that we are going to change a nonlocal variable.

If we use the nonlocal keyword, Python will try to find the str_msg variable in the enclosing until it finds it.

Additionally, Python will not search for the variable in the global scope.

Check the example below:

str_msg = 'This is the global scope'

def outer_func():
    print(str_msg)

    def inner_func():
        nonlocal str_msg
        str_msg = 'This is the inner scope'
        print(str_msg)

    inner_func()
    print(str_msg)


outer_func()

Output:

SyntaxError: no binding for nonlocal 'str_msg' found

In the example above, we have used the nonlocal keyword for the str_msg variable inside the inner_func function.

And Python searches for that variable in the outer_func function’s enclosing scope.

Since Python can’t find the str_msg variable in the scope of the outer_func function, Python will not look further into the global scope because of the nonlocal keyword.

If you try to run the code, it will cause an error.

Python nonlocal example programs

Example 1:

In this example, we test what happens when a nonlocal variable refers to a global variable.

str_msg = 'Global'


def outer_func():

    def inner_func():
        nonlocal str_msg
        str_msg = 'Inner'
        print(str_msg)

    inner_func()


outer_func()

Output:

SyntaxError: no binding for nonlocal 'str_msg' found

Example 2:

In this example, we’ll determine which variable nonlocal refers to when several functions with identically named variables are nested within one another.

def outer_func():
    str_msg = 'Outer'

    def middle_func():
        str_msg = 'Middle'

        def inner_func():
            nonlocal str_msg
            print(str_msg)
            str_msg = 'Inner'
            print(str_msg)

        inner_func()

    middle_func()
    print(str_msg)


outer_func()

Output:

Middle
Inner
Outer

Example 3:

In this example, we will create a counter that may be reused.

# Our counter function
def counter():
  c = 0 # Local counter variable
   
  # This function manipulate the
  # local c variable, when called
  def count():
    nonlocal c
    c += 1
    return c
   
  # Return the count() function to manipulate
  # the local c variable on every call
  return count
 
# Assign the result of counter() to
# a variable which we use to count up
my_counter = counter()
for i in range(3):
  print(my_counter())
print('End of my_counter')
   
# Create a new counter
new_counter = counter()
for i in range(3):
  print(new_counter())
print('End of new_counter')

Output:

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.

Advantages of nonlocal keyword Python

One advantage of nonlocal keywords in Python is that they help access the variables in the upper scope.

When the referenced variable is used more than once, the memory address of the variable is also used more than once, which saves memory.

Disadvantages of nonlocal keyword Python

In Python, the problem with nonlocal keywords is that you can’t use them to refer to global or local variables.

Also, nonlocal keywords can only be used inside structures that are nested inside each other.


FAQs

What does nonlocal mean in Python?

The nonlocal keyword is used to work with variables inside nested functions, where the variable should not belong to the inner function. Use the keyword nonlocal to declare that the variable is not local.

What is the nonlocal variable Python?

In Python, nonlocal variables refer to all those variables that are declared within nested functions. The local scope of a nonlocal variable is not defined. This essentially means that the variable exists neither in the local scope nor in the global scope.

Is nonlocal the same as global in Python?

Nonlocal is similar in meaning to global. But it takes effect primarily in nested methods. It means “not a global or local variable.” So it changes the identifier to refer to an enclosing method’s variable. Here Method2() uses nonlocal to reference the “value” variable from method().

Summary

In summary, Python nonlocal scopes are the enclosing scopes of inner functions.

If we want to modify a variable from a nonlocal scope, we have to use the nonlocal keyword.

And lastly, Python will search for the nonlocal variable in the enclosing scopes.

It will not search for the variable in the global scope.

If you found the information in this article useful, please consider sharing it with others who may find it useful as well.

Leave a Comment