Lesson · Functions
Scope & Name Resolution
66 min readScope & Name Resolution
Name lookup follows the LEGB model: local, enclosing, global, then built-ins. Scope rules matter for closures, nested functions, shadowing, and controlled rebinding with `global` or `nonlocal`.
Learning goals
- Walk the LEGB ladder: local, enclosing, global, built-ins, and say which binding a lookup finds first.
- Trace the worked example's nested
outerandinnerframes and label whichnamebinding each assignment targets. - Explain what
nonlocalrebinds and why the module-levelnameis still"global"afterouter()runs. - Predict when an assignment inside a function creates a new local binding instead of reaching an outer name.
- Explain how a nearer binding shadows a built-in such as
lenorprint.
Mental model
A read walks that ladder from the innermost frame outward and stops at the first frame that owns the name; a write normally touches only the innermost frame, which is why nonlocal or global must announce any rebinding of an outer name. Shadowing falls out of the same rule: a nearer binding simply hides an outer or built-in one. The labels in the fence match the worked example, where inner's lookup of name stops at outer's frame, two steps before the module namespace.
One lookup, four namespaces, first hit wins
Local, then Enclosing, then Global, then Built-ins
Mental model
the same mechanism as a compact list
lookup inside inner() ↓ 1. Local inner's own bindings, such as local_only ↓ 2. Enclosing outer's bindings, such as name = "enclosing" ↓ 3. Global the module's bindings, such as name = "global" ↓ 4. Built-ins len, print, and the rest of the built-in names first frame with the binding wins
Core idea
The organizing idea is that lookup and assignment move in opposite directions: reads climb the LEGB ladder from the innermost frame outward and stop at the first binding found, while writes stay in the current frame unless global or nonlocal redirects them. Shadowing, stateful closures, and the UnboundLocalError from reading a name that is assigned later all follow from that one asymmetry.
Local scope
A function call creates local bindings for its parameters and assignments. These names normally disappear when the frame is released, although closures can keep selected bindings alive.
Enclosing scope
Nested functions can read bindings from lexically enclosing function scopes. nonlocal allows controlled rebinding of such a name.
Global scope
A module's namespace is the global scope for functions defined in that module. Reading global constants is common; mutating global state increases coupling.
Built-in scope
If a name is not found in local, enclosing, or global scopes, Python searches built-ins such as len and print. A nearer binding can shadow a built-in name.
LEGB rule
Python resolves an unqualified name by searching Local, Enclosing, Global, then Built-in namespaces. Assignment normally creates or changes a name in the current local scope.
global
global tells Python that assignments to a named variable inside the current function target the module-global namespace. Use it sparingly because it increases shared mutable state.
nonlocal
nonlocal targets a binding in the nearest enclosing function scope. It is useful for stateful closures when mutating an object is not enough.
Shadowing
Shadowing binds a local name that hides an outer or built-in name during lookup. It is legal but can make code harder to understand when the hidden name is widely recognized.
Closures preview
A closure keeps references to names from an enclosing function scope after that outer call has returned. The captured binding, not a frozen snapshot of its value, is what matters.
Walkthrough
name = "global"binds in the module namespace beforeouteris defined, so both functions can read it while no nearer binding exists.- Inside
outer,name = "enclosing"creates a local binding for that frame, shadowing the globalnamefor every lookup made whileouterruns. nonlocal nameininnertargets the nearest enclosing function binding, soname = "changed"rewritesouter's local, whilelocal_onlyis a plain local ofinnerthat disappears wheninnerreturns.- Predict before running: what the two
printstatements show, especially why the module-levelnameends as"global".
Experiments to try
- Remove
nonlocal namefrominner, run again, and explain whyouter's binding now keeps the value"enclosing"all the way to the return. - Add
len = 99insideouterand calllen([1])there; read theTypeErrorand explain that the local binding shadows the built-in for the whole frame. - Move a
print(name)to the top ofouter, beforename = "enclosing"; the read raisesUnboundLocalErrorbecause the later assignment madenamelocal to the entire frame. - Add
calls = 0at module level anddef bump(): global calls; calls += 1; return calls; callbump()twice, then deleteglobal callsand explain the newUnboundLocalError.
Playable lesson
Lab: LEGB scope explorer
Display Local, Enclosing, Global, and Built-ins namespaces and highlight the first namespace that satisfies each lookup.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
LEGB scope explorer
empty
empty
empty
Resolve a name
Predict first
Where does a bare `len(...)` call resolve?
Four namespaces, searched in one fixed order: Local, Enclosing, Global, then Built-ins. The first one that holds the name wins.
Common mistakes
- Reading a name above an assignment to it in the same function: the assignment makes the name local to the whole frame, so the early read raises
UnboundLocalErrorinstead of falling back to an outer binding. - Expecting an assignment inside a function to update the module namespace: without
globalthe write creates a local binding, and the outer name keeps its old value with no error to warn you. - Treating
nonlocalas a synonym forglobal:nonlocalresolves to the nearest enclosing function binding and raisesSyntaxErrorwhen no enclosing function defines that name. - Shadowing a built-in by accident, for example naming a parameter
listor assigninglenlocally: the nearer binding hides the built-in for the entire call, so later uses fail withTypeError.
Practice: Easy
- Run the worked example unchanged and write down both printed lines; for each line, name the frame that owned each value at that moment.
- Delete
nonlocal namefrominner, run again, and state which binding the assignment insideinnernow changes and which valueouterreturns. - Add a
print(name)at the top ofouter, beforename = "enclosing", record the error it raises, then move the print after the assignment and record the value.
Practice: Medium
- Replace
nonlocal namewithglobal nameand rerun; explain why the last line of output changes and whyouter's own binding no longer does. - Write
def make_counter(): count = 0containingdef step(): nonlocal count; count += 1; return countand returningstep; call the result twice and explain why the second call still sees the first call's count. - Shadow a built-in inside a function:
def summarize(values): list = values; return list, then add alist("ab")call insidesummarizeand explain theTypeErrorfrom the shadowed name.
Practice: Hard
- Build a scope tracer with a module-level
state = []and nestedouterandinnerfunctions whereinnerappends tostatewithoutglobaland rebinds a separate scalar withnonlocal; predict which operations mutate the shared object and which rebind which frame, then verify with prints inside every frame. - Design a shadowing experiment across scopes: shadow three different built-ins, one in a local frame, one in an enclosing function, and one at module level, then record which call sites resolve to the shadow and which still reach the built-in.
- Extend the worked example with a third nested level so
nonlocalhas two enclosing candidates: place the binding in only one of them, state which framenonlocalpicks and why, then move the binding and test your claim.
Lesson checklist
- I can walk the LEGB ladder and name the frame that supplies a given lookup.
- I can trace which
namebinding each assignment in the worked example targets. - I can explain what
nonlocalrebinds and why the module-levelnamestays"global". - I can spot a shadowed built-in and restore the original lookup.
Remember
Reads and writes move in opposite directions: a lookup walks Local, Enclosing, Global, then Built-ins and stops at the first frame with the binding, while an assignment stays in the current frame unless `global` or `nonlocal` redirects it. That asymmetry explains shadowing, stateful closures, and the `UnboundLocalError` raised when a function reads a name it also assigns later.
Interview angles
What is the main purpose of **Local scope**?+
A function call creates local bindings for its parameters and assignments. These names normally disappear when the frame is released, although closures can keep selected bindings alive.
What should you pay attention to when using **Enclosing scope**?+
Nested functions can read bindings from lexically enclosing function scopes. nonlocal allows controlled rebinding of such a name.
How does **Global scope** fit into this lesson?+
A module's namespace is the global scope for functions defined in that module. Reading global constants is common; mutating global state increases coupling.
Why does a name read above an assignment in the same function raise `UnboundLocalError`?+
The assignment makes the name local to the whole frame, so the compiler treats every reference to it in that function as a local lookup. When the early read executes, the local binding has no value yet, and Python raises instead of falling back to the enclosing or global binding.