Names and binding
Binding is the act of attaching a name to an object inside a namespace. Assignment is only one of about a dozen operations that bind, and Python decides which namespace a name belongs to when it compiles your code, not when it runs it.
Detailed Explanation
The language reference does not talk about variables very much. It talks about names and bindings, and that vocabulary is more precise. A name is an identifier. A binding is an entry in a namespace that connects that identifier to an object. A namespace is a mapping from strings to objects, usually an actual dictionary you can look at with globals() or vars(obj).
Assignment is the obvious way to create a binding, but there are many others, and forgetting one is a common source of confusion. All of these bind a name:
count = 0anda, b = b, a— assignment, including unpackingdef handler(): ...andclass Order: ...— the name of the function or classimport jsonandfrom pathlib import Path— the module or the imported objectfor order in orders:— the loop targetwith open(path) as handle:— theastargetexcept ValueError as exc:— the exception name, which Python deletes again at the end of the blockif (rows := fetch()) :— the walrus operator- a function's parameters, bound fresh on every call
match command: case {"user": name}:— capture patterns in structural matching
The second half of the idea is timing. When CPython compiles a function, it scans the whole body and sorts every name into a category: local, enclosing-function cell, global, or builtin. That decision is baked into the bytecode. It never re-examines the question at runtime.
This is why one line at the bottom of a function can change the meaning of a line at the top. If the body assigns to total anywhere, total is local everywhere in that function, so reading it earlier raises UnboundLocalError rather than finding the module-level total. The name exists as a slot; the slot has nothing in it yet. global total or nonlocal total overrides the classification explicitly.
Closures work through the same machinery. When an inner function reads a name from its enclosing function, the compiler stores that name in a cell rather than a plain slot, and both functions share the cell. The crucial detail is that a closure captures the cell, not the value at the moment of definition. Ten lambdas built in a loop over i all share one cell and all see the final i. Binding a default argument (lambda i=i: i) captures the value instead, because default arguments are evaluated once at definition time.
A few smaller rules round it out. del name removes the binding and leaves the object alive for anyone else still referencing it. A for loop target survives the loop, so item is still bound after the last iteration. Comprehensions, by contrast, run in their own scope in Python 3, so their loop variable does not leak. Class bodies get a namespace that becomes the class __dict__, but that namespace is not an enclosing scope for methods, which is why a method must write self.rate or Order.rate rather than a bare rate.
Code Examples
# One assignment at the bottom changes the whole function.
request_count = 100 # module-level binding
def bump_broken():
print(request_count) # reads a LOCAL slot that is still empty
request_count = 1 # this line is what makes the name local
try:
bump_broken()
except UnboundLocalError as exc:
print(type(exc).__name__) # UnboundLocalError
def bump_fixed():
global request_count # explicit: use the module-level binding
request_count += 1
bump_fixed()
print(request_count) # 101# Closures capture the cell, not the value. This trips up everyone once.
late = [lambda: index for index in range(3)]
print([fn() for fn in late]) # [2, 2, 2] <- all share one cell
# Default arguments are evaluated at definition time, so they snapshot.
early = [lambda index=index: index for index in range(3)]
print([fn() for fn in early]) # [0, 1, 2]
def make_counter():
hits = 0
def record():
nonlocal hits # rebind the ENCLOSING name, not a new local
hits += 1
return hits
return record
counter = make_counter()
counter()
print(counter()) # 2# Namespaces really are dictionaries.
cache_size = 256
print("cache_size" in globals()) # True
# A for target outlives the loop; a comprehension variable does not.
for log_line in ["GET /", "POST /login"]:
pass
print(log_line) # POST /login
lengths = [len(entry) for entry in ["a", "bb"]]
print("entry" in dir()) # False <- comprehension has its own scope
# del unbinds the name only.
backup = {"retries": 3}
config = backup
del config
print("config" in dir(), backup) # False {'retries': 3}Common Gotchas
`UnboundLocalError` is a scoping message, not a typo message
it means the compiler classified the name as local because something in the body assigns to it. Read the whole function before assuming the name is missing, and reach for `global` or `nonlocal` only when you genuinely intend to mutate outer state.
Loops plus lambdas plus late binding
building callbacks inside a loop and expecting each to remember its own iteration value is the classic version of this bug. It shows up in event handlers, retry wrappers, and argparse defaults. Bind the value with a default argument or `functools.partial`.
`except ... as exc` unbinds `exc` at the end of the block
Python deletes the name to break a reference cycle with the traceback. If you need the exception later, assign it to another name inside the handler.
A class body is not an enclosing scope
methods cannot see class-level names as bare identifiers, and a comprehension inside a class body cannot see them either. Qualify with `self.` or the class name.