Why does a default list remember previous function calls?
Python 3.10+; standard library only. GIL discussion refers to conventional CPython builds, not optional free-threaded builds.
Detailed answer
Default argument expressions are evaluated when the def statement runs, not on each call. A mutable default therefore belongs to the function and is shared across calls.
Use None as the default and create a new list inside the function when no list was supplied. An explicitly supplied list can still be intentionally mutated if the contract says so.
The same issue applies to dictionaries, sets and default objects. A shared cache may be deliberate, but it should be explicit and have a documented lifetime.
Internal working
A function stores defaults in __defaults__. Calls missing an argument reuse the reference stored there; appending changes that shared object.
Practical scenario
A student submission service appends validation errors to a default list and exposes one student's errors in the next request.
def collect(x, items=None):
if items is None:
items = []
items.append(x)
return items
print(collect(1), collect(2))Common mistakes
- Using items = items or [] when an empty supplied list must be preserved.
- Replacing [] with another mutable object.
Key takeaways
- Defaults evaluate at definition.
- Use None and an explicit branch.
- Document mutation ownership.
Follow-up challenges
- When might shared defaults be intentional?
- How does a dataclass default_factory differ?