nonlocal Scope in Python with Example

In Python, we can define function within function which is called nested function. When we create nested function then there will be some scopes which are neither local nor global. Such scopes are known as nonlocal scopes in Python.

This article explains nonlocal scope in Python with example.

To understand the concept of nonlocal scope consider a following python program:


a = 20

def outer_function():
    b = 30
    # Printing from non-local scope
    print('Outer: a = %d and b=%d' %(a,b))
    def inner_function():
        c = 40
        # printing from local scope
        print('Inner: a = %d, b=%d and c = %d' %(a,b,c))

# printing from global scope
print('Global: a = %d' %(a))

# function call


Global: a = 20
Outer: a = 20 and b=30
Inner: a = 20, b=30 and c = 40


In this example, both functions outer_function and inner_function have access to the global and built-in scopes as well as their respective local scopes.

But inner_function has access to its enclosing scope i.e. scope of outer_function and this scope is neither global nor local and hence it is known as nonlocal scope.

In this example inner_function can access global variable a, nonlocal variable b and local variable c.

Here variable b is nonlocal for inner_function but local for outer_function.