Python global and nonlocal: Modifying Outer Scope Variables
What you’ll learn
Section titled “What you’ll learn”- The LEGB lookup rule and how Python finds a name.
- The
globalkeyword: rebinding a module-level name from inside a function. - The
nonlocalkeyword: rebinding a name in an enclosing function scope (closures). - Why
globalis discouraged and the bugs it causes. - Safer alternatives: return values, class attributes, and mutable containers.
Summary
Section titled “Summary”Python resolves names by the LEGB rule — Local, Enclosing, Global, Built-in — reading outward. By default, assigning to a name inside a function makes it a local variable, even if a same-named global exists; the global only shadows, it is not reassigned. The global keyword tells Python that a name refers to a module-level variable, so assignment rebinds the global. The nonlocal keyword (Python 3.0+) does the same for a name in an enclosing function scope, which is what lets a closure update its captured state. Both keywords are about rebinding assignment, not about reading. global is widely discouraged because it creates hidden, module-wide state that is hard to test and reason about; nonlocal is the right tool for small closures and counters, and there are usually better alternatives for anything larger.
The problem it solves
Section titled “The problem it solves”Two scoping problems. First, a function needs to update a module-level counter or config value. Without global, assigning to the name creates a local, leaving the global untouched (and UnboundLocalError if you read it before assigning). global makes the assignment hit the module variable. Second, a nested function needs to update a variable defined in its enclosing function — a closure that counts calls, or accumulates a value. Without nonlocal, assigning in the inner function makes a local that shadows the outer variable, so the closure cannot actually change the captured state. nonlocal declares that the name refers to the enclosing scope, so the inner function can rebind it.
Both keywords solve the same underlying problem: “I want to assign to a name that is not local to this function,” for the two outer scopes that matter — global (module) and enclosing function.
How it works
Section titled “How it works”Python looks up a name in order: Local (the function’s own scope), Enclosing (outer function scopes, for nested defs), Global (module), Built-in (builtins like len). For reading, the first match wins. For assignment, a bare name is local by default.
global
Section titled “global”count = 0
def increment(): global count count += 1
increment()print(count) # 1Without global, count += 1 would raise UnboundLocalError: Python sees an assignment to count, makes it local, then reads it before it is bound. global says “count is the module-level name,” so the assignment rebinds it.
nonlocal
Section titled “nonlocal”def make_counter(): n = 0
def step(): nonlocal n n += 1 return n
return step
counter = make_counter()print(counter()) # 1print(counter()) # 2Without nonlocal, n += 1 in step would make n a local of step (and raise UnboundLocalError on read-before-assign). nonlocal says “n is the enclosing function’s variable,” so step updates the captured n and the counter persists across calls.
global vs nonlocal vs bare assignment
Section titled “global vs nonlocal vs bare assignment”- Bare assignment in a function: creates or updates a local.
global x: assignment updates the module-levelx.nonlocal x: assignment updates the nearest enclosing function’sx(it must exist in an enclosing scope, elseSyntaxError).
Result shape and edge cases:
globalis a declaration; it takes effect for the whole function body even if written at the bottom (conventionally it goes at the top).- A name declared
globalbut never assigned in the module still works if you only read it; assigning creates the module attribute. nonlocalcannot reach the module level — it targets only enclosing function scopes. If no enclosing function has the name, it is aSyntaxError.globalandnonlocalonly affect assignment (rebinding). Reading works through LEGB without them, and mutating a mutable object does not need them — you are not rebinding the name, you are mutating the object it points to.
Realistic example
Section titled “Realistic example”OrdersPortal has a module-level feature flag and a processed-orders counter that handlers update (global), plus a closure that batches orders until a threshold and then flushes (nonlocal).
# global: module-level config the handlers updatefeature_flags = {"new_pricing": False}processed = 0
def enable_new_pricing(): global processed feature_flags["new_pricing"] = True processed = 0 # reset the counter when the flag flips
def handle_order(order_id): global processed processed += 1 if feature_flags["new_pricing"]: return f"{order_id} priced with new engine" return f"{order_id} priced with old engine"Note that feature_flags is a dict; we mutate it, so no global is needed for that. processed is an int (immutable), so rebinding it needs global.
A closure with nonlocal that batches orders until a threshold, then flushes:
def make_batcher(size): batch = []
def add(order_id): nonlocal batch batch.append(order_id) if len(batch) >= size: ready = batch batch = [] # rebind the enclosing name via nonlocal return ready return None
return add
flush = make_batcher(3)print(flush("ORD-1")) # Noneprint(flush("ORD-2")) # Noneprint(flush("ORD-3")) # ['ORD-1', 'ORD-2', 'ORD-3']print(flush("ORD-4")) # NoneHere batch = [] rebinds the enclosing batch through nonlocal, so the next batch starts empty. Without nonlocal, batch = [] would create a local, and the captured batch would keep growing.
Production patterns
Section titled “Production patterns”- Prefer returning values over
global: have functions return new state and let the caller assign. This is testable and explicit. - Use class attributes for shared mutable state: a class with
self.processedis clearer than a module global and namespaces the state. - Use a mutable container (dict, list) instead of
globalfor a counter you update from functions — mutating the container does not needglobal, only rebinding an int does. A class is usually clearer still. nonlocalfor small closures and counters is idiomatic; for anything larger, prefer a class.- Keep
globaldeclarations at the top of the function for readability.
Common mistakes
Section titled “Common mistakes”- Forgetting
globaland gettingUnboundLocalErroroncount += 1(read-before-assign because Python madecountlocal). - Forgetting
nonlocalin a closure and silently shadowing the outer variable — the closure does not update the captured state. - Using
globalto share state across functions, creating hidden coupling that is hard to test. - Declaring
nonlocalfor a name with no enclosing binding —SyntaxError. - Thinking you need
globalto mutate a list or dict — you do not; only rebinding the name needs it.mylist.append(x)works withoutglobal. - Overusing globals for “configuration” that cannot then be safely changed at runtime across threads.
When to use it and when not to
Section titled “When to use it and when not to”Use global when:
- You genuinely need to rebind a module-level name (rare; usually a class or a config object is better).
- Writing a small script or REPL where a module-level counter is convenient.
Avoid global when:
- The state is shared across many functions — use a class or a module-level object with methods.
- Testability matters — globals make functions depend on hidden state and the order of calls.
- The “global” is really configuration — use a config object or environment variables.
Use nonlocal when:
- A closure needs to update captured state (counters, accumulators, small state machines).
Avoid nonlocal when:
- The closure’s state is more than a couple of variables — promote to a class.
Compatibility
Section titled “Compatibility”global has been in Python since the start. nonlocal was added in Python 3.0 (PEP 3104) and is absent from Python 2.x. Both work on 3.9 through 3.14. The LEGB rule is unchanged across versions.
Interview questions
Section titled “Interview questions”-
What is the LEGB rule, and in what order does Python look up a name? Local, Enclosing, Global, Built-in. Python checks the function’s own scope first, then enclosing function scopes (for nested
defs), then the module (global), then built-ins. The first match wins for reading; for assignment a bare name is local by default. -
What does
globaldo, and what happens without it incount += 1inside a function whencountis a module-level int?globaltells Python the name refers to the module-level variable, so the assignment rebinds it. Without it, Python sees an assignment tocount, treats it as local, andcount += 1readscountbefore it is bound — raisingUnboundLocalError. -
What is the difference between
globalandnonlocal, and why doesnonlocalnot reach the module level?globalbinds to a module-level name;nonlocalbinds to a name in an enclosing function scope.nonlocalcannot reach the module level because it targets only enclosing function scopes — if no enclosing function has the name, it is aSyntaxError. Usenonlocalfor closure state,globalfor module state. -
Senior scenario: a teammate writes a closure that should count how many orders it processes, but the count never increases — it stays 0. The inner function does
count = count + 1with nononlocal. What is happening, and what are two ways to fix it (one withnonlocal, one without)? Withoutnonlocal, the assignmentcount = count + 1makescounta local of the inner function — so the captured outercountis never changed, and the read-before-assign also raisesUnboundLocalError. Fix one: declarenonlocal countso the assignment rebinds the enclosing variable. Fix two (nononlocal): keep the state in a mutable container —counter = {"n": 0}in the enclosing function andcounter["n"] += 1inside; mutating the dict does not rebind the name, so nononlocalis needed. A class with an instance attribute is the more readable choice if the state grows beyond a single counter.
Key takeaways
Section titled “Key takeaways”- LEGB is the lookup order; bare assignment makes a name local.
globalrebinds a module-level name;nonlocalrebinds an enclosing function’s name.- Mutating a mutable object needs neither — only rebinding does.
globalcreates hidden, hard-to-test state; prefer return values, classes, or config objects.nonlocalis idiomatic for small closures and counters; promote to a class for larger state.
Related pages
Section titled “Related pages”- splat operator —
*args/**kwargsand parameter scoping - keyword-only — explicit keyword boundaries in function signatures
- walrus operator —
:=assignment and its scoping rules