`global` and `nonlocal`
global tells a function that an assignment should update a module-level name. nonlocal tells a nested function that an assignment should update a name in an enclosing function. Without them, assignment creates a local.
Detailed Explanation
Python treats assignment as the act that creates a local name. total = total + 1 inside a function does not mean "update the total I can see". It means "this function has a local called total". If you only wanted to read a global, you do not need a declaration. If you want to write one, you do.
global name is that declaration. It can appear anywhere in the function, and it applies to the whole function. After global total, total = 0 rebinds the module's total. Several names can share one statement: global a, b.
nonlocal is the same idea one scope inward. A nested function that writes total = total + 1 would otherwise create its own local and hide the outer total. nonlocal total updates the nearest enclosing function that already has that name. It cannot skip to the module; that is global. It cannot create a new enclosing name; the name must already exist.
Both statements exist because Python chose compile-time scope, not "assign to whatever I last saw". The compiler needs to know, for every name in a function, which namespace it belongs to. The declarations are that decision made explicit.
Using global for shared mutable state is usually a sign the design wants an object, a class attribute, or a function that returns the new value. A module-level counter works in a script and becomes painful in tests, because tests share the module. Prefer passing state in and returning it, or storing it on an object.
nonlocal is the honest tool for closures that accumulate. A decorator that counts calls, a callback that updates a flag, a parser that advances an index — those are enclosing locals, not globals. If the inner function only mutates a list or dict from the outer scope, you do not need nonlocal. Mutation is not assignment. seen.append(item) writes into the object; seen = [] rebinds the name.
Code Examples
served = 0
def serve() -> int:
global served
served += 1
return served
print(serve(), serve()) # 1 2
print(served) # 2def make_limiter(max_calls: int):
calls = 0
def allow() -> bool:
nonlocal calls
if calls >= max_calls:
return False
calls += 1
return True
return allow
gate = make_limiter(2)
print(gate(), gate(), gate()) # True True Falsedef collect():
seen = [] # enclosing list
def add(item: str) -> list:
seen.append(item) # mutation, no nonlocal needed
return seen
return add
log = collect()
print(log("login")) # ['login']
print(log("pay")) # ['login', 'pay']Common Gotchas
`nonlocal` cannot create a name
the enclosing function must already bind it. If it does not, you get `SyntaxError: no binding for nonlocal 'x' found`.
`global` plus `nonlocal` on one name is illegal
a name cannot be both. Pick the namespace you mean.
Mutation is not rebinding
`counter[0] += 1` on a one-element list works without `nonlocal`. It is a workaround, not a style to copy. Prefer `nonlocal` or an object.
Reading a global needs no declaration
`global` is only for assignment (and for `del` of that name).