Python nonlocal Keyword

Usage

If a variable is declared in an enclosing (outer) function, it is nonlocal to nested (inner) function.

The nonlocal keyword is used to update these variables inside a nested function.

The usage of nonlocal is very similar to that of global, except that the former is primarily used in nested functions.

Syntax

nonlocal var1,var2,

Python global keyword parameters
ParameterConditionDescription
var1,var2,…RequiredList of identifiers you want to declare nonlocal

Basic Example

Here’s a basic example that tries to reassign enclosing function’s local variable inside a nested function.

Example:

# enclosing function
def f1():
    x = 42
    
    # nested function
    def f2():
        x = 0
        print(x)    # x is 0
    f2()
    print(x)        # x is still 42
    
f1()

Here, the value of existing variable x didn’t change. Because, Python created a new local variable named x that shadows the variable in the outer scope.

Preventing that behavior is where the nonlocal keyword comes in.

Example:

# enclosing function
def f1():
    x = 42
    
    # nested function
    def f2():
        nonlocal x
        x = 0
        print(x)    # x is now 0
    f2()
    print(x)        # x remains 0
    
f1()

The x inside the nested function now refers to the x outside the function, so changing x inside the function changes the x outside it.