Nonlocal Statement in Python

The nonlocal statement in Python is a powerful feature that allows a function to modify a variable that is not local to it but is defined in an enclosing function. This is particularly useful when dealing with nested functions, where you might want to modify a variable from an outer function within an inner function.

Overview

The nonlocal statement is used to refer to a variable in the closest enclosing scope that is not global. This means that it allows a function to access and modify variables that are defined in an enclosing function, but not at the global level. This is different from the global statement, which is used to refer to variables at the top level of the module.

Example Usage

Consider the following example, which demonstrates the use of the nonlocal statement:

Listing 9.1 File nonlocal.py

g_var = 0               #A
nl_var = 0               #B
print("top level-> g_var: {0} nl_var: {1}".format(g_var, nl_var))
def test():
    nl_var = 2              #C
    print("in test-> g_var: {0} nl_var: {1}".format(g_var, nl_var))
    def inner_test():
 
        global g_var         #D
        nonlocal nl_var      #E
        g_var = 1
        nl_var = 4
        print("in inner_test-> g_var: {0} nl_var: {1}".format(g_var,
                                                              nl_var))
        
    inner_test()
    print("in test-> g_var: {0} nl_var: {1}".format(g_var, nl_var))
 
test()
print("top level-> g_var: {0} nl_var: {1}".format(g_var, nl_var))
#A g_var in global scope.
#B nl_var in global scope.
#C nl_var in test (not global).
#D use of global makes g_var in inner_test bind to top level g_var.
#E use of nonlocal makes nl_var bind to nl_var in test.

Explanation

  • Global Variable (g_var): The variable g_var is defined at the global scope. The global statement in inner_test makes g_var in inner_test refer to this top-level g_var. When g_var is modified in inner_test, it affects the global g_var.

  • Nonlocal Variable (nl_var): The variable nl_var is defined in the test function. The nonlocal statement in inner_test makes nl_var in inner_test refer to the nl_var in test. This allows inner_test to modify nl_var in the test function.

Output

The output of the above code will be:

top level-> g_var: 0 nl_var: 0
in test-> g_var: 0 nl_var: 2
in inner_test-> g_var: 1 nl_var: 4
in test-> g_var: 0 nl_var: 4
top level-> g_var: 1 nl_var: 0

This output shows how the global and nonlocal statements affect the variables in different scopes. The global statement allows inner_test to modify the global g_var, while the nonlocal statement allows it to modify nl_var in the test function.