Scope determines which binding a name refers to at a particular place in a program.
Follow local, enclosing, global and built-in lookup, and distinguish nonlocal updates from changes to a module binding.
The name rate can exist in several scopes at once. A pricing function needs
to read the intended one and preserve an explicit zero override. First identify
where Python binds the name, then trace where a read gets its value. That order
explains shadowing, UnboundLocalError, and the different jobs of global and
nonlocal.

A three-city pricing engine
A pricing tool has one module-wide default tax rate, but each region can override it. Build the override once per region, and let every price lookup inside that region read it — without ever touching the global directly:
price_it never mentions TAX_RATE. It asks for rate, and Python's search
finds it one step out, in region_pricing — the Enclosing scope — and
never even looks at the module. That's the order that trips people up: E is
checked before G, not after.
LIMIT = 100
def make_checker():
LIMIT = 50 # a same-named local in the ENCLOSING function
def over():
return LIMIT # which one does this find?
return over
check = make_checker()
print(check())Preparing this topic’s interactive investigation…
A score tracker with a memory
A game keeps a running high score per session. nonlocal doesn't mean
"global" — it means "the nearest enclosing scope that already has this
name", which can be one level out or several:
wrap_round reads the enclosing outer_round binding but reassigns no shared name, so it needs no
nonlocal at all — the rule only cares about names a function itself
assigns. nonlocal climbs outward one enclosing scope at a time and stops
at the first one that already defines the name; it never reaches the module
level (that's what global is for).
UnboundLocalErrorRun it and read the error. Then let record remember the best score between calls.
Locate the binding before tracing execution
LEGB describes ordinary function-body name resolution, but it is not a search that skips an uninitialised local and continues outward. First classify the binding from the function's syntax; then follow execution to see whether that binding has received a value.
The assignment makes rate local throughout quote, including the path on
which that assignment never runs. Python does not fall back to the module's
rate. An explicit initial value inside quote, or an explicit enclosing
configuration passed in, makes both paths defined.
global targets the defining module's namespace, not every module in the
application; it can create a new module binding. nonlocal requires an existing
binding in an enclosing function scope. An attribute assignment such as
settings.rate = 0 changes an object and is not an assignment to the name
settings; the aliasing lesson explains why no scope declaration is needed.
For the pricing task, override_rate or TAX_RATE would wrongly discard the
valid override 0.0. The explicit is not None test distinguishes a supplied
zero from an absent override. Test default, zero, and nonzero overrides, then
explain which binding each inner call reads.
Shadowing a name you didn't mean to
A function that reuses a built-in's name doesn't fail right away — it fails later, somewhere that name is needed:
def summarise(items):
list = len(items) # shadows the built-in list() inside this function
empty = list([]) if list == 0 else "n/a"
return empty
print(summarise([]))Never name a variable the same as a built-in you (or code near it) still
need: list, sum, id, type, input, dict are the usual victims.
Common scope bugs, named
- UnboundLocalError from a read-before-write. If a function assigns to a
name anywhere — even in an
ifthat doesn't run — that name is local for the whole function, and reading it before the assignment line fails. - A
forloop variable outlives the loop. Unlike many languages, Python has no block scope:for i in range(5): ...leavesi= 4 readable right after the loop, in the same scope. It does not leak into an enclosing or global scope though — only within the block's own function/module. global/nonlocalmust come before the first use in that function, and only affects the function it's written in — not functions it calls.
Quick practice
x = "outer"
def show():
print(x)
x = "inner"
show()def counter_demo():
n = 0
def bump():
n = n + 1 # looks like it updates n...
return n
return bump
tick = counter_demo()
print(tick())UnboundLocalErrorMake add actually accumulate across calls.
for i in range(3):
last_seen = i
print(last_seen)🎯 Your turn
Write priced_list(bases, override_rate=None). It builds one region
pricer (like region_pricing above) and returns the price of every base
amount in bases, each rounded to 2 decimals, at 18% tax by default — or at
override_rate when one is given.
priced_list([1000])→[1180.0]priced_list([1000], override_rate=0.0)→[1000.0]
Hint: the module already has TAX_RATE = 0.18. Build one inner
price_it closure that reads rate from its enclosing scope, then apply it
to every base with a list comprehension: [price_it(b) for b in bases].
Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below goes from a single safe read to a full closures-and-globals tour.
Practice — level up
0/5 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
A module-level SERVICE_FEE = 25 is already defined. Write total_with_fee(amount) that returns amount + SERVICE_FEE. You are only READING the global, so no global keyword is needed.
Write make_running_max() returning a function check(x) that returns True when x is strictly higher than every value seen so far (or is the first value), else False. Then running_max_flags(values) builds ONE tracker and returns the list of flags for each value in order.
Write make_id_generator(prefix) returning next_id(), which returns f"{prefix}-{n}" with n starting at 1 and going up by 1 on every call. Then batch_ids(prefix, count) builds ONE generator and returns a list of its first count ids.
A module-level LEDGER = [] holds entries. Write record_entry(amount) that appends amount to LEDGER (a mutation — no global needed) and reset_ledger() that empties it by REASSIGNING LEDGER = [] (an assignment — needs global). Then ledger_after(amounts) resets the ledger, records every amount in order, and returns the final ledger as a list.
A module-level TRACKERS_MADE = 0 counts every tracker built during one tour. Write make_level_tracker() returning a pair (advance, status) sharing one enclosing level (starting at 1): advance() adds 1 to level and returns it (nonlocal); status() returns {"level": level, "trackers_made": TRACKERS_MADE} (reads level from Enclosing, TRACKERS_MADE from Global — no assignment, so no keyword there). Building a tracker must bump the global TRACKERS_MADE by 1 (needs global). Then tracker_tour(how_many, advances) resets TRACKERS_MADE to 0 (needs global too), builds how_many trackers in a row, calls advance() on the LAST one advances times, and returns its final status().