Sub topic 3
Local names inside a function
This chapter assumes you can define and call functions, use print, work with lists, and read a simple traceback. It covers how Python decides that a name inside a function is local, and what that means for the code you write.
What makes a name local
A local name is a name that exists only while one call of a function runs. Python creates a new local namespace each time you call the function. It discards that namespace when the call returns.
A name becomes local in a function when the function binds it. Binding operations include:
- Assignment:
x = 1 - Augmented assignment:
x += 1 - Function parameters
forloop targetsimportstatements and nesteddeforclassstatements
Parameters are local names that Python binds for you at call time.
Local names do not touch globals
If a function assigns to a name that also exists at module level, the two names are separate. The assignment creates a local name and leaves the global alone.
x = "global"
def show():
x = "local"
print(x)
show()
print(x)
# Output:
# local
# globalInside show, x refers to the local string. After the call, the local namespace is gone, and the module-level x still holds "global".
Reading a name you never assign
A function can read a global name if it never assigns that name. Lookup starts in the local namespace, finds nothing, and falls through to the global namespace.
count = 0
def read_count():
return count
print(read_count())
# Output: 0The rule: the whole body decides
Python decides whether a name is local before it runs the function. It scans the whole function body at compile time. If the body binds a name anywhere, that name is local everywhere in the function, including lines above the assignment.
count = 0
def increment():
count += 1
increment()
# UnboundLocalError: cannot access local variable 'count' where it is not associated with a valuecount += 1 means count = count + 1. Because the line binds count, Python treats count as local for the entire body. The right-hand side then reads a local that has no value yet, so the call fails. The exact error wording varies between Python versions.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `UnboundLocalError` on `+=` | Augmented assignment makes the name local | Pass the value in and return the result |
| Global value unchanged after a call | The function assigned to a new local name | Return the new value and assign it at the call site |
| Error only on some code paths | A conditional assignment makes the name local on every path | Assign a default at the top of the function |
The last row surprises many people. In this function, label is local even when the if branch does not run:
def describe(n):
if n > 0:
label = "positive"
return label
print(describe(5))
# Output: positive
print(describe(-1))
# UnboundLocalError: cannot access local variable 'label' where it is not associated with a valueA better pattern: parameters and return values
Pass data into a function through parameters and send results out with return. This keeps the function's behavior visible in its signature.
def increment(count):
return count + 1
count = 0
count = increment(count)
count = increment(count)
print(count)
# Output: 2A later chapter covers the global statement, which is the other way to fix the increment error above. For most code, the version above is easier to test and reason about.
Exercise
This function raises UnboundLocalError when called. Why, and how do you fix it without using global?
total = 10
def add(n):
total = total + n
return total
Show answer
The assignment total = total + n binds total, so Python treats it as local for the whole function. The right-hand side reads the local total before it has a value. Fix it by passing the value in: def add(total, n): return total + n, then call total = add(total, 5).
Exercise
What does this code print, and why? x = 5 def f(): print(x) def g(): x = 7 print(x) f() g() print(x)
Show answer
It prints 5, 7, 5. Function f only reads x, so lookup finds the global. Function g assigns x, which creates a separate local name, so the global stays 5.