Python's mutable default argument trap (and how to fix it)
Why def f(items=[]) shares one list between every call, how it causes bugs that look impossible, and the None pattern that fixes it, with dataclasses and class attributes too.
This is one of the most famous bugs in Python, and nearly everyone writes it at least once. It shows up in interviews, in code reviews, and in a production incident in the Python Developer career path, where drivers start seeing other drivers' delivery stops.
The bug
def add_stop(stop, route=[]):
route.append(stop)
return route
print(add_stop("Altona"))
print(add_stop("Wandsbek"))You'd expect two separate one-item lists. You get:
['Altona']
['Altona', 'Wandsbek']The second call "remembers" the first.
Why it happens
Python evaluates default values once, when the def statement runs, and stores the resulting
object on the function. Every call that doesn't pass route gets that same list. append changes
the list in place, so the change is visible to every later call.
You can even see it:
print(add_stop.__defaults__) # (['Altona', 'Wandsbek'],)Immutable defaults (numbers, strings, None, tuples) are safe, because nothing can change them in
place. The trouble is with lists, dicts, sets and your own mutable objects.
The fix: None as a sentinel
def add_stop(stop, route=None):
if route is None:
route = []
route.append(stop)
return routeNow every call without a route gets a brand-new list. Callers who pass their own list still can.
Use is None, not if not route:, or an empty list passed on purpose would be replaced too.
The same bug in disguise
Dataclasses refuse a plain mutable default and tell you to use a factory:
from dataclasses import dataclass, field
@dataclass
class Route:
van: str
stops: list = field(default_factory=list) # a new list per RouteClass attributes behave like defaults: one object shared by every instance.
class Cart:
items = [] # shared by every cart!
def __init__(self):
self.items = [] # one list per cartCaches that should not be caches. A module-level results = [] that a function appends to
works the same way: state leaks between calls, and between tests.
How to catch it
- A test that calls the function twice. Most of these bugs pass a single test and fail the second. See testing with pytest.
- Linters:
ruffandpylintflag mutable defaults (rule B006 / W0102). - Code review: it's on every reviewer's list. Add it to yours with our code review checklist.
Is it ever useful?
Occasionally people use it on purpose as a quick cache. Don't: it's surprising to every reader.
Use functools.cache, or make the state explicit in a class. Clever code that looks like a bug
gets "fixed" by the next person.
Questions and answers
- Why is a mutable default argument a problem in Python?
- Default values are evaluated once, when the def statement runs, not on every call. A list or dict used as a default is therefore one shared object: anything one call adds to it is still there in the next call.
- How do I fix a mutable default argument?
- Use None as the default and create a new object inside the function: def f(items=None): if items is None: items = []. In dataclasses, use field(default_factory=list).
Practise it
Read next
- Python dataclasses, enums and datetimes: modelling a business domain
Model real business data in Python with dataclasses, frozen value objects, StrEnum for fixed choices, type hints checked by mypy, and timezone-aware datetimes.
- Testing with pytest: run, read and write Python tests
How to run pytest, read a failing test, select tests with markers and -k, share setup with fixtures, cover many cases with parametrize, and test exceptions.
- Code review checklist for junior developers
What senior engineers look for in a code review, as a practical checklist: correctness, edge cases, tests, naming, structure and performance, with C++-specific points.