Sub topic 6
Why Assignment Makes a Name Local
This chapter assumes you can define and call functions, read a simple traceback, and know that a name in Python refers to an object. It builds on the LEGB lookup rule from the previous chapter. Here you learn why a function can read a global name but fails when it also assigns to that name.
The puzzle
Reading a global from inside a function works:
count = 0
def read_count():
return count
print(read_count())
# Output: 0Adding one line of assignment to a similar function breaks it:
count = 0
def increment():
count += 1
try:
increment()
except UnboundLocalError as err:
print(type(err).__name__)
print(err)
# Output:
# UnboundLocalError
# cannot access local variable 'count' where it is not associated with a valueThe wording of the message depends on your Python version. Before 3.11 it read local variable 'count' referenced before assignment.
You might expect count += 1 to read the global count, add one, and store the result. Python does not work that way. The error comes from a decision Python makes before your function ever runs.
The rule: any binding makes the name local for the whole function
When Python compiles a function body, it scans the whole body and collects every name that is bound in it. A name is bound when something attaches it to an object. Every name bound anywhere in the function is local to that function. This holds from the first line to the last, including lines before the assignment.
The decision is made once, at compile time, by reading the source text. It does not depend on which branches run or in what order.
For increment, the statement count += 1 is a binding, so count is local. When the function runs, the first thing += does is read the local count. That local slot is still empty, so Python raises UnboundLocalError. The global count is never consulted.
What counts as a binding
Plain = is the most common binding, but it is not the only one. Each of these makes the name local if it appears anywhere in the function body:
| Form | Example | Name that becomes local |
|---|---|---|
| Assignment | `total = 0` | `total` |
| Augmented assignment | `total += 1` | `total` |
| Loop target | `for item in data:` | `item` |
| Import | `import json` | `json` |
| Function or class definition | `def helper():` | `helper` |
| With target | `with open(p) as f:` | `f` |
| Exception target | `except ValueError as e:` | `e` |
| Assignment expression | `if (n := len(s)) > 3:` | `n` |
| Deletion | `del cache` | `cache` |
| Parameter | `def f(count):` | `count` |
Attribute and item assignment are not bindings of the name. obj.attr = 1 and items[0] = 1 change an object that the name refers to. They do not make obj or items local. The chapter on mutation versus rebinding covers this in detail.
Seeing the decision yourself
Python records its classification on the function's code object. You can read it:
count = 0
def read_count():
return count
def increment():
count += 1
print(read_count.__code__.co_varnames)
print(read_count.__code__.co_names)
print(increment.__code__.co_varnames)
# Output:
# ()
# ('count',)
# ('count',)co_varnames lists the local names, which includes parameters. co_names lists the names looked up outside the function, such as globals. In read_count, count appears in co_names, so it is a global lookup. In increment, it appears in co_varnames, so it is a local slot.
Order and execution do not matter
Because classification happens by reading the source, a binding that never runs still counts. This surprises many people:
x = 10
def f():
print(x)
if False:
x = 5
try:
f()
except UnboundLocalError:
print("x is local, even though the assignment never ran")
# Output: x is local, even though the assignment never ranThe print(x) line comes first and the assignment is in a branch that never executes. Python still treats x as local throughout f, so the read fails.
The same thing happens with a conditional assignment that sometimes runs:
def label(score):
if score >= 50:
result = "pass"
return result
print(label(80))
try:
print(label(20))
except UnboundLocalError as err:
print("failed:", err)
# Output:
# pass
# failed: cannot access local variable 'result' where it is not associated with a valueHere no global is involved at all. The name result is local and, on the failing path, never received a value. This is the same error with a different cause. When you see UnboundLocalError, check two possibilities: you meant to use a global, or some path through the function skips the assignment.
A sneaky variant: imports inside functions
An import is a binding, so it can shadow a module imported at the top of the file:
import os
def show():
print(os.name)
import os
try:
show()
except UnboundLocalError as err:
print("failed:", err)
# Output: failed: cannot access local variable 'os' where it is not associated with a valueThe inner import os makes os local to show, so the earlier os.name fails. This often appears when someone adds a late import to a long function and an earlier line stops working. Move the import to the top of the module or to the top of the function.
Fixing it
You have three choices, in rough order of preference.
Pass the value in and return the result. This keeps the function free of hidden dependencies on module state:
count = 0
def increment(current):
return current + 1
count = increment(count)
count = increment(count)
print(count)
# Output: 2Declare the name global. The global statement tells the compiler that the name refers to the module-level binding, so the assignment rebinds the global instead of creating a local:
count = 0
def increment():
global count
count += 1
increment()
increment()
print(count)
# Output: 2The global statement must appear before the name is used in the function. Python reports a SyntaxError if a name is used or assigned before its global declaration. The next chapter covers global in more detail.
Use a different local name. If you only want a working copy of the global, give it its own name:
count = 0
def next_value():
value = count + 1
return value
print(next_value())
print(count)
# Output:
# 1
# 0Common mistakes
- Assuming
+=reads the global. An augmented assignment is both a read and a binding. The binding decides the scope. - Debugging the wrong line. The traceback points to the line that reads the name, which may be far from the assignment that made it local. Search the whole function for any binding of that name.
- Adding a binding in a refactor. Renaming a variable, adding a loop with the same target name, or adding an import can turn an earlier global read into an error.
- Using a name only on some paths. Assign a default before the
if, or return early, so every path gives the name a value. - Reaching for
globalfirst. It makes the error go away, but it also makes the function depend on and change shared state, which complicates testing.
Summary of the working model
- Python classifies names per function, at compile time, from the source text.
- A parameter or any binding anywhere in the body makes a name local for the whole body, unless a
globalornonlocalstatement says otherwise. - Names that are only read are looked up at run time through the enclosing, global, and built-in scopes.
- Reading a local before it has a value raises
UnboundLocalError.
Exercise
Predict what this code prints, or which error it raises, and say why. Then fix it so that it prints 3 without using global. total = 0 def add(values): for v in values: total += v return total print(add([1, 2]))
Show answer
It raises UnboundLocalError. The augmented assignment total += v is a binding, so total is local to add for the whole function body. The first execution of the loop body reads the local total before it has a value. One fix is to start from a local: define total = 0 inside add before the loop, so the function body binds and initializes its own name, and print(add([1, 2])) prints 3. Another fix is to return sum(values).