Skip to content

Python global and nonlocal: Modifying Outer Scope Variables

  • The LEGB lookup rule and how Python finds a name.
  • The global keyword: rebinding a module-level name from inside a function.
  • The nonlocal keyword: rebinding a name in an enclosing function scope (closures).
  • Why global is discouraged and the bugs it causes.
  • Safer alternatives: return values, class attributes, and mutable containers.

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.

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.

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.

count = 0
def increment():
global count
count += 1
increment()
print(count) # 1

Without 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.

def make_counter():
n = 0
def step():
nonlocal n
n += 1
return n
return step
counter = make_counter()
print(counter()) # 1
print(counter()) # 2

Without 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.

  • Bare assignment in a function: creates or updates a local.
  • global x: assignment updates the module-level x.
  • nonlocal x: assignment updates the nearest enclosing function’s x (it must exist in an enclosing scope, else SyntaxError).

Result shape and edge cases:

  • global is 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 global but never assigned in the module still works if you only read it; assigning creates the module attribute.
  • nonlocal cannot reach the module level — it targets only enclosing function scopes. If no enclosing function has the name, it is a SyntaxError.
  • global and nonlocal only 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.

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 update
feature_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")) # None
print(flush("ORD-2")) # None
print(flush("ORD-3")) # ['ORD-1', 'ORD-2', 'ORD-3']
print(flush("ORD-4")) # None

Here 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.

  • 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.processed is clearer than a module global and namespaces the state.
  • Use a mutable container (dict, list) instead of global for a counter you update from functions — mutating the container does not need global, only rebinding an int does. A class is usually clearer still.
  • nonlocal for small closures and counters is idiomatic; for anything larger, prefer a class.
  • Keep global declarations at the top of the function for readability.
  • Forgetting global and getting UnboundLocalError on count += 1 (read-before-assign because Python made count local).
  • Forgetting nonlocal in a closure and silently shadowing the outer variable — the closure does not update the captured state.
  • Using global to share state across functions, creating hidden coupling that is hard to test.
  • Declaring nonlocal for a name with no enclosing binding — SyntaxError.
  • Thinking you need global to mutate a list or dict — you do not; only rebinding the name needs it. mylist.append(x) works without global.
  • Overusing globals for “configuration” that cannot then be safely changed at runtime across threads.

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.

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.

  1. 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.

  2. What does global do, and what happens without it in count += 1 inside a function when count is a module-level int? global tells Python the name refers to the module-level variable, so the assignment rebinds it. Without it, Python sees an assignment to count, treats it as local, and count += 1 reads count before it is bound — raising UnboundLocalError.

  3. What is the difference between global and nonlocal, and why does nonlocal not reach the module level? global binds to a module-level name; nonlocal binds to a name in an enclosing function scope. nonlocal cannot reach the module level because it targets only enclosing function scopes — if no enclosing function has the name, it is a SyntaxError. Use nonlocal for closure state, global for module state.

  4. 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 + 1 with no nonlocal. What is happening, and what are two ways to fix it (one with nonlocal, one without)? Without nonlocal, the assignment count = count + 1 makes count a local of the inner function — so the captured outer count is never changed, and the read-before-assign also raises UnboundLocalError. Fix one: declare nonlocal count so the assignment rebinds the enclosing variable. Fix two (no nonlocal): keep the state in a mutable container — counter = {"n": 0} in the enclosing function and counter["n"] += 1 inside; mutating the dict does not rebind the name, so no nonlocal is needed. A class with an instance attribute is the more readable choice if the state grows beyond a single counter.

  • LEGB is the lookup order; bare assignment makes a name local.
  • global rebinds a module-level name; nonlocal rebinds an enclosing function’s name.
  • Mutating a mutable object needs neither — only rebinding does.
  • global creates hidden, hard-to-test state; prefer return values, classes, or config objects.
  • nonlocal is idiomatic for small closures and counters; promote to a class for larger state.