Sobes.tech
Junior — Middle

Is it possible to explain the concept of nonlocal and how it is used in Python?

sobes.tech AI

Answer from AI

In Python, the keyword nonlocal is used inside nested functions to indicate that the variable we are referring to is in an outer (but not global) scope.

Usually, if a nested function assigns a value to a variable, Python considers it local. To modify a variable from an outer function, it must be declared as nonlocal.

Example:

def outer():
    count = 0
    def inner():
        nonlocal count
        count += 1
        print(count)
    inner()
    inner()

outer()
# Output:
# 1
# 2

Without nonlocal, attempting to modify count inside inner would cause an error, because Python would consider count a local variable that was not initialized inside inner.

Thus, nonlocal allows working with variables from outer, but not global, scopes, which is useful for closures and nested functions.