Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Keyword nonlocal

Make a name refer to the nearest existing binding in an enclosing function scope, allowing rebinding from a nested function.

Version: Python 3.14; repository image, production runtime not attested

Syntax

nonlocal total

Make a name refer to the nearest existing binding in an enclosing function scope, allowing rebinding from a nested function.

The binding persists in a returned closure. A module global alone does not satisfy nonlocal and a missing enclosing binding causes SyntaxError at compilation.

Each new outer call can create independent state.

Examples

def counter(start):
    total = start
    def next_value():
        nonlocal total
        total += 1
        return total
    return next_value
a, b = counter(0), counter(7)
print(a(), a(), b())
try:
    compile("def bad():\n    nonlocal absent", "<example>", "exec")
except SyntaxError:
    print("missing binding")

Result

1 2 8
missing binding

Each new outer call can create independent state.

Sources