Functions

Global and Nonlocal

global and nonlocal choose which outer binding assignment should update.

global tells assignment to update a module-level binding. Without it, count += 1 would try to assign a local count.

Source

count = 0

def bump_global():
    global count
    count += 1

bump_global()
print(count)

Output

1
B · BUILT-ING · GLOBALE · ENCLOSINGL · LOCAL
Name lookup walks LEGB — local, enclosing, global, built-in — outward, returning the first binding it finds.

nonlocal tells assignment to update a binding in the nearest enclosing function scope. This is useful for small closures that keep state.

Source

def make_counter():
    total = 0
    def bump():
        nonlocal total
        total += 1
        return total
    return bump

counter = make_counter()
print(counter())
print(counter())

Output

1
2

Notes

See also

Run the complete example

Example code

Expected output

1
1
2

Execution time appears here after you run the example.