Sub topic 6
The mutable default argument pitfall
This chapter assumes you can define and call functions, know how lists, dicts and None behave, and can read a simple traceback. It also assumes you know that a default value lets a caller leave an argument out. Here you will see why that feature gives surprising results when the default is a list or a dict.
The symptom
Here is a function that appends an item to a list and returns the list. The caller can supply a list, and otherwise the function uses an empty one.
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("a")) # ['a']
print(add_item("b")) # ['a', 'b']
print(add_item("c")) # ['a', 'b', 'c']Each call omits items, so you would expect each call to start from an empty list. Instead the list keeps growing across calls. Nothing in the call site hints at this, and the bug often shows up far from where it was introduced. A common case is a web handler that returns one user's data in another user's response.
The cause: one object, created once
The previous chapter showed that a default expression runs when the def statement executes, not when the function is called. Python evaluates [] once, creates one list, and stores it on the function object. Every call that omits the argument binds the parameter to that same list.
You can see the stored object directly:
def add_item(item, items=[]):
items.append(item)
return items
print(add_item.__defaults__) # ([],)
add_item("a")
print(add_item.__defaults__) # (['a'],)
add_item("b")
print(add_item.__defaults__) # (['a', 'b'],)The default is not copied on each call. The tuple in __defaults__ holds a reference to the list, and items.append(...) mutates that list in place. The function object lives as long as the module does, so the list lives that long too. The data is shared by every caller in the process.
Which defaults are affected
The problem needs two conditions together: the default object is mutable, and the function mutates it (or hands it out so someone else can). An immutable default cannot change, so sharing it is harmless.
| Default value | Mutable? | Safe as a default? |
|---|---|---|
| `0`, `3.5`, `True` | No | Yes |
| `"text"`, `b"bytes"` | No | Yes |
| `None` | No | Yes |
| `(1, 2)`, `frozenset()` | No | Yes |
| `[]`, `list()` | Yes | No |
| `{}`, `dict()` | Yes | No |
| `set()`, `bytearray()` | Yes | No |
| An instance of your own class | Usually | Usually no |
A tuple is only shallowly immutable. A default such as ([],) cannot be reassigned, but the list inside it can still be mutated. Check the contents, not only the outer type.
Dicts fail in the same way as lists:
def count(word, seen={}):
seen[word] = seen.get(word, 0) + 1
return seen
print(count("x")) # {'x': 1}
print(count("x")) # {'x': 2}
print(count("y")) # {'x': 2, 'y': 1}Variations that look different
The default leaks without being mutated by the function
The function itself may never mutate the default. If it returns the default, the caller can mutate it:
def get_tags(tags=[]):
return tags
a = get_tags()
a.append("urgent")
print(get_tags()) # ['urgent']The mutation happens in the caller's code, which makes it harder to trace back to the signature.
Defaults that should change per call but do not
The same timing rule affects any default that depends on when or where the call happens, not just containers.
import time
def log(message, timestamp=time.time()):
return (timestamp, message)
first = log("start")
time.sleep(0.05)
second = log("later")
print(first[0] == second[0]) # Truetime.time() ran once, at definition. Both calls report the same timestamp. The fix is the same as for lists: do not compute the value in the signature.
Dataclasses refuse the mistake
dataclasses rejects list, dict and set defaults when the class is defined, because the same sharing problem would apply to every instance:
from dataclasses import dataclass, field
@dataclass
class Ticket:
title: str
tags: list = field(default_factory=list)
t1 = Ticket("a")
t2 = Ticket("b")
t1.tags.append("x")
print(t2.tags) # []Writing tags: list = [] raises ValueError: mutable default <class 'list'> for field tags is not allowed: use default_factory. Plain functions have no such guard. Python will accept items=[] without complaint.
The standard fix
Use None as the default, and create the fresh object inside the function body, where it runs on every call:
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item("a")) # ['a']
print(add_item("b")) # ['b']The next chapter covers this pattern in detail, including what to do when None is itself a meaningful argument. Two rules are worth keeping in mind now. Compare with is None, not if not items:. The second form also replaces an empty list that the caller passed in on purpose, so the function would silently stop mutating the caller's list. The other rule is that the None default does not stop callers from passing their own list:
shared = ["x"]
add_item("y", shared)
print(shared) # ['x', 'y']The function mutates the caller's list here. That is ordinary aliasing, and it is a separate design question from the default-value bug. If your function should not change its input, copy it first with items = list(items), or build and return a new list.
When a shared default is intended
Because the default persists between calls, you can use it as private state on purpose. A memoizing function is the classic case:
def fib(n, _cache={0: 0, 1: 1}):
if n not in _cache:
_cache[n] = fib(n - 1) + fib(n - 2)
return _cache[n]
print(fib(30)) # 832040This works, but it has drawbacks. Callers can pass a _cache argument by accident, the intent is easy to miss in review, and the state cannot be reset cleanly. functools.cache expresses the same idea without those problems. If you rely on a shared default anyway, name the parameter with a leading underscore and leave a comment saying the sharing is deliberate.
Detecting the problem
You can check a function you did not write by looking at its stored defaults:
import inspect
def risky(a, b=[], *, c={}):
pass
print(risky.__defaults__) # ([],)
print(risky.__kwdefaults__) # {'c': {}}
for name, param in inspect.signature(risky).parameters.items():
if isinstance(param.default, (list, dict, set, bytearray)):
print("mutable default:", name)
# mutable default: b
# mutable default: cLinters also catch this. Flake8-bugbear reports it as B006, and Pylint reports it as dangerous-default-value (W0102). Running one of them in CI is cheaper than finding the bug in production.
Common mistakes in fixing it
- Writing
items = items or []. This replaces an empty list the caller passed with a new one, so the caller's list is never filled. - Moving the default into the body but not guarding it, as in
items = []at the top of the function. This ignores the argument entirely. - Fixing the list but forgetting a sibling parameter like
options={}in the same signature. - Assuming that
copy.copyon the default at call time is enough. It is a valid fix if you copy before mutating, but it still leaves the shared original exposed to anyone who reads__defaults__. TheNonepattern avoids the shared object altogether.
Exercise
This function should return a new list of the scores seen so far, starting from an empty list when no history is given. Explain why the second call prints the wrong result, then rewrite the function so the output is [90] and then [75]. def record(score, history=[]): history.append(score) return history print(record(90)) print(record(75))
Show answer
The empty list is created once, when the def statement runs, and is stored in record._defaults_. Both calls omit history, so both append to that one list. The second call therefore prints [90, 75]. Fix it with a None sentinel: def record(score, history=None): if history is None: history = [] history.append(score) return history Now each call that omits history creates its own list, so the output is [90] and then [75].
Exercise
Write a function stamp(message, when=None) that returns a tuple of the time and the message. When when is not given, it must use the time of the call, not the time the function was defined. Why does def stamp(message, when=time.time()) fail?
Show answer
The expression time.time() in the signature runs once, when def executes, so every call without when reuses that one value. Use the sentinel pattern:
import time
def stamp(message, when=None):
if when is None:
when = time.time()
return (when, message)
The call to time.time() is now inside the body, so it runs on every call.