Functions
Global and Nonlocal
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
1nonlocal 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
2Notes
- Assignment inside a function is local unless declared otherwise.
- Prefer
nonlocalfor closure state and avoidglobalunless module state is truly intended. - Passing values and returning results is usually easier to test than rebinding outer names.
See also
Run the complete example
Expected output
1
1
2
Execution time appears here after you run the example.