Python Scope: local, enclosing, global, and built-in (LEGB)
What you’ll learn
Section titled “What you’ll learn”- The LEGB rule and the order Python searches scopes for a name.
- How to read a global from inside a function.
- How to modify a global with the
globalkeyword. - How to modify an enclosing variable with the
nonlocalkeyword. - Why variable shadowing causes subtle bugs.
- Why mutable default arguments are a scope- and lifetime-related bug.
- How closures capture variables, and how to avoid scope pitfalls.
Prerequisites
Section titled “Prerequisites”- Python 3.9 or newer installed (
python --version). - Familiarity with functions, variables, and basic data structures.
Step 1 — The LEGB rule
Section titled “Step 1 — The LEGB rule”Python resolves every name using the LEGB rule. When you reference a name, the interpreter searches scopes in this fixed order: Local (inside the current function), Enclosing (any outer function scopes, for nested functions), Global (module level), then Built-in (names like len and print that Python provides). It returns the first match it finds, which is why a local name can hide a global one of the same spelling. Reading a name never creates it; only assignment does, and assignment inside a function makes that name local to the function.
app_name = "OrdersPortal" # Global scope
def show_app(): print(app_name) # reads the global — no assignment here
show_app() # OrdersPortalVerify: Run the function and confirm it prints OrdersPortal. Then delete the global line and rerun; the function raises NameError, proving it was reading the global.
Step 2 — Local scope and the UnboundLocalError trap
Section titled “Step 2 — Local scope and the UnboundLocalError trap”A name assigned anywhere in a function is local to that function for the whole function body, even on lines that run before the assignment. This is the classic trap: a function that reads a global and then assigns to a name of the same spelling does not read the global — it treats the name as local, and the early read happens before the local is bound.
count = 10
def bad(): print(count) # UnboundLocalError — 'count' is local because of the line below count = 20
# bad() # uncomment to see the error
def good(): print(count) # 10 — reads the global, because there is no assignment here
good()Verify: Uncomment the bad() call. It raises UnboundLocalError, while good() prints 10. The difference is purely whether an assignment to count exists in the function body.
Step 3 — Modifying globals with global
Section titled “Step 3 — Modifying globals with global”To rebind a global from inside a function, declare it with the global keyword. Without that declaration, an assignment silently creates a local instead. Use global sparingly: shared mutable state that any function can change is hard to reason about, and most uses are better replaced by returning a value from the function.
order_count = 0
def record_order(): global order_count order_count += 1
record_order()record_order()print(order_count) # 2Verify: Comment out the global order_count line. The function now raises UnboundLocalError on the +=, proving that global is what lets the function reach the outer name.
Step 4 — Enclosing scope and nonlocal
Section titled “Step 4 — Enclosing scope and nonlocal”When functions are nested, an inner function can read names from the outer (enclosing) function. To rebind an enclosing name — one that is not global — use nonlocal. This is the key tool for building counters and stateful closures, because it lets the inner function update the outer function’s variable rather than create a new local.
def make_counter(start=0): count = start
def step(): nonlocal count count += 1 return count
return step
orders_today = make_counter()print(orders_today()) # 1print(orders_today()) # 2print(orders_today()) # 3Verify: Each call returns a number one higher than the last, which shows nonlocal updates the same count instead of resetting it.
Step 5 — Shadowing built-ins
Section titled “Step 5 — Shadowing built-ins”The built-in scope holds names like list, dict, id, and type. If you assign to one of these names at module level or inside a function, you shadow the built-in for that scope, and later code that relied on the built-in breaks in confusing ways. The fix is to pick a different name.
# Shadowing the built-in 'id' — now id() no longer returns an object identityid = "ORD-001"
# print(id([])) # TypeError: 'str' object is not callable
# Fix: rename and recover the built-in by deleting the shadowdel idprint(id("ORD-001")) # some integer — the built-in works againVerify: After id = "ORD-001", calling id([]) fails; after del id, it works again. That confirms assignment shadowed the built-in and deletion restored it.
Step 6 — Mutable defaults: a scope and lifetime bug
Section titled “Step 6 — Mutable defaults: a scope and lifetime bug”A default argument value is created once, when the function is defined, and shared across every call that uses the default. This is a lifetime issue tied to scope: the default object lives in the function’s enclosing scope and persists between calls, so mutations accumulate. The safe pattern is to use a sentinel like None and create a fresh container inside the body.
def add_order(order, basket=[]): basket.append(order) return basket
print(add_order("ORD-001")) # ['ORD-001']print(add_order("ORD-002")) # ['ORD-001', 'ORD-002'] — same list, not a new one!
# Correct patterndef add_order_safe(order, basket=None): if basket is None: basket = [] basket.append(order) return basket
print(add_order_safe("ORD-003")) # ['ORD-003']print(add_order_safe("ORD-004")) # ['ORD-004'] — a fresh list each callVerify: The first version reuses the same list across calls, so the second call sees ORD-001 already inside it. The safe version returns a clean list every time, confirming the fix.
Step 7 — Closures capture variables, not values
Section titled “Step 7 — Closures capture variables, not values”A closure is an inner function that remembers the names from its enclosing scope even after the outer function has returned. It captures the variable, not a snapshot of its value, so changes to the enclosing variable are visible later. The most common surprise is a loop that creates several closures: they all share the same loop variable, so they all see its final value.
def make_status_logger(status): def log(order_id): return f"{order_id}: {status}" return log
pending_log = make_status_logger("pending")shipped_log = make_status_logger("shipped")print(pending_log("ORD-001")) # ORD-001: pendingprint(shipped_log("ORD-001")) # ORD-001: shippedVerify: The two loggers were created from the same factory but capture different status values, so they print different strings for the same order ID. This shows each closure binds its own enclosing variable.
Complete working example
Section titled “Complete working example”Save as scope_demo.py and run with python scope_demo.py (Python 3.9+):
"""OrdersPortal: a scope-safe counter and an order-status registry."""
# Module-level global, modified only through the functions that declare ittotal_revenue = 0.0
def add_revenue(amount: float) -> None: global total_revenue total_revenue = round(total_revenue + amount, 2)
# A closure factory that captures an enclosing variable and updates itdef make_registry(): orders = {} # enclosing scope
def register(order_id, status): nonlocal orders orders[order_id] = status return dict(orders) # return a copy, not the live dict
return register
add_revenue(149.99)add_revenue(49.99)print(f"Total revenue: ${total_revenue}") # Total revenue: $199.98
registry = make_registry()print(registry("ORD-001", "pending")) # {'ORD-001': 'pending'}print(registry("ORD-002", "shipped"))# {'ORD-001': 'pending', 'ORD-002': 'shipped'}
# Mutable-default bug, demonstrated and avoideddef append_item(item, items=None): if items is None: items = [] items.append(item) return items
print(append_item("A")) # ['A']print(append_item("B")) # ['B'] — fresh list, no leakTotal revenue: $199.98{'ORD-001': 'pending'}{'ORD-001': 'pending', 'ORD-002': 'shipped'}['A']['B']Common mistakes
Section titled “Common mistakes”- Forgetting
globalwhen reassigning a global.count += 1inside a function raisesUnboundLocalErrorunless you declareglobal count. (Plain reads do not need it.) - Reading then assigning the same name. The assignment makes the name local for the whole function, so the earlier read fails with
UnboundLocalError. Rename the local or useglobal/nonlocal. - Mutable default arguments.
def f(x=[])shares one list across calls. Usex=Noneand create the container in the body. - Shadowing a built-in. Naming a variable
list,id,type, ordictbreaks later code that calls the built-in. - Closures over a loop variable. Several closures created in one loop share the loop variable and see its final value. Bind it with a default argument:
lambda x=i: x.
Best practices for avoiding scope bugs
Section titled “Best practices for avoiding scope bugs”Keep functions self-contained: take inputs as arguments, return outputs, and avoid mutating globals. When you must share state, prefer a small class or a closure factory over scattered global declarations, because the state is then owned by one object you can reason about. Use type hints and meaningful names that do not collide with built-ins, and reach for nonlocal only inside a deliberate closure, not as a shortcut around passing a parameter.
Next steps
Section titled “Next steps”- Functions basics —
def, arguments, and return values - Lambda functions — small closures in one line
- Decorators intro — functions that wrap functions, built on closures
Related pages
Section titled “Related pages”- Dictionaries — a safer way to hold shared state than globals
- Classes basics — instance state instead of module globals
- global — the
globalkeyword in depth - Type hints — annotating the names you bind