Full answer
python
def add_bad(x, items=[]):
items.append(x)
return items
print(add_bad(1))
print(add_bad(2))
print(add_bad.__defaults__)
def add_good(x, items=None):
if items is None:
items = []
items.append(x)
return items
print(add_good(1))
print(add_good(2))Output:
text
[1]
[1, 2]
([1, 2],)
[1]
[2]The second call to add_bad returns [1, 2] because the list created at definition time is stored in add_bad.__defaults__ and reused. The fixed version creates a fresh list on each call that does not pass one. The same trap applies to dicts, sets and any mutable object, including a default of datetime.now(), which is evaluated once and then frozen. Linters such as Ruff (rule B006) flag mutable defaults automatically.
python
def add_bad(x, items=[]):
items.append(x)
return items
print(add_bad(1))
print(add_bad(2))
print(add_bad.__defaults__)
def add_good(x, items=None):
if items is None:
items = []
items.append(x)
return items
print(add_good(1))
print(add_good(2))Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- Defaults are evaluated once at definition
- Mutable defaults are shared between calls
- Use None and create inside
- Linters detect this
Common mistakes
- Using [] or {} as defaults
- Using datetime.now() as a default
Follow-ups
- When is a shared default intentional?
- How do dataclasses handle mutable defaults?
Tips
- Point at __defaults__