Sub topic 6
Why assignment makes a name local
This chapter assumes you can define and call functions, read a simple traceback, and know the LEGB lookup order (local, enclosing, global, built-in). Here you will see why a function that reads a global works, but a function that assigns to the same name fails.
Reading works, assigning breaks
A function can read a global name it never assigns, because lookup falls through from local scope to global scope.
count = 0
def read_count():
return count
print(read_count())
# Output: 0Now add an assignment to the same name:
count = 0
def increment():
count += 1
increment()
# UnboundLocalError: cannot access local variable 'count' where it is not associated with a valueThe exact wording of the error varies between Python versions. The error type, UnboundLocalError, does not.
The rule: Python decides before running
Python compiles a function body before it runs it. During compilation it scans the whole body for assignments. Any name that is bound anywhere in the function is marked local for the entire function. Binding includes:
x = ...andx += ...for x in ...import xanddef xinside the functionwith ... as xandexcept ... as x
At run time, a local name is looked up only in the local scope. It never falls through to the global scope. In increment, the line count += 1 means count = count + 1. Python must read count first, but the local count has no value yet, so it raises the error.
The error can appear far from the assignment
Because the decision covers the whole body, an assignment placed later in the function breaks an earlier read:
total = 10
def report():
print(total)
total = 20
report()
# UnboundLocalError: cannot access local variable 'total' where it is not associated with a valueThe print line looks fine on its own. The assignment two lines below is what turned total into a local name. This is why the traceback points at the read, not at the assignment that caused the problem.
Assignment without a read is not an error
If the function only assigns, nothing fails. It simply creates a separate local name, and the global stays unchanged:
x = "global"
def show():
x = "local"
print(x)
show()
print(x)
# Output:
# local
# globalThis is a common source of silent bugs. You may intend to update a global, but the function quietly changes a local copy of the name and discards it.
Fixing it
You have three options, in rough order of preference:
- Pass the value in as a parameter and return the result.
- Declare the name with
globalif the function truly must rebind a module-level name. The next chapter covers this. - Rename the local variable if you meant to keep the two separate.
Here is option 1:
count = 0
def increment(value):
return value + 1
count = increment(count)
print(count)
# Output: 1The function has no hidden dependency on module state, so it is easier to test.
Common mistakes
| Symptom | Cause | Fix |
|---|---|---|
| Error on `n += 1` in a function | `+=` binds `n`, so it is local | Pass `n` in and return it, or use `global` |
| Error on a `print` before a later assignment | Assignment later in the body makes the name local | Rename one of the variables |
| Global unchanged after calling a function | Function assigned a new local name | Return the value, or use `global` |
Exercise
Why does this code raise UnboundLocalError, and what is the smallest change that makes show() print 5 without using global?
level = 5
def show():
print(level)
level = level + 1
Show answer
The assignment level = level + 1 makes level local for the whole function, so print(level) reads a local that has no value yet. Renaming the assigned variable fixes it: replace the last line with new_level = level + 1. Now level is only read, so it resolves to the global and prints 5.