Sub topic 6
The mutable default argument pitfall
This chapter assumes you can define and call functions, know lists, dicts and None, and can read a simple traceback. It also assumes you know that a default value is evaluated once, when the def statement runs. That fact causes the bug described here.
The symptom
This function should return a list containing the new item:
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("a")) # ['a']
print(add_item("b")) # ['a', 'b'] (the same list is reused)The second call omitted items, yet the result still contains "a". Nothing in the function body creates a new list, so the output looks wrong. The cause is in how the default is stored.
The mechanism
Python evaluates [] once, when def runs, and stores the resulting list object on the function. Every call that omits items binds the parameter to that same object. append mutates the object in place, so the change is still there on the next call.
You can see the stored default directly:
def add_item(item, items=[]):
items.append(item)
return items
add_item("a")
add_item("b")
print(add_item.__defaults__) # (['a', 'b'],)The default itself has changed. It is no longer the empty list you wrote in the signature.
When it matters
The pitfall needs two conditions together:
- The default is a mutable object, such as a list, dict or set, or an instance of a class you wrote.
- The function mutates it, or returns it so the caller can mutate it.
Defaults that are immutable are safe: numbers, strings, tuples, None and True or False. Rebinding a name such as count = count + 1 creates a new object and leaves the stored default alone. Only in-place changes such as append, update, add or item assignment cause trouble.
A dict default fails the same way:
def tag(name, registry={}):
registry[name] = len(registry)
return registry
print(tag("x")) # {'x': 0}
print(tag("y")) # {'x': 0, 'y': 1}Why Python behaves this way
Evaluating defaults at definition time is consistent: the def statement runs once and builds the function object, defaults included. It also keeps calls cheap, because the default is not recomputed each time. The same rule means a default such as time.time() is fixed at definition and does not give the time of each call.
Spotting it in review
Look for these forms in a signature:
=[],={}and=set()=list()and=dict(), which are also evaluated once=SomeClass(), which creates one shared instance
Many linters flag these. In flake8, the bugbear plugin reports rule B006 for them.
The fix, in brief
Use None as a placeholder and create the real object inside the function body. Each call then gets its own list:
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 more detail, including why the check uses is None instead of a truthiness test.
Exercise
This function is meant to count how many times each word is seen across one call. Why does the second call print a count of 2 for "hi", and how would you fix the signature? def count(word, seen={}): seen[word] = seen.get(word, 0) + 1 return seen print(count("hi")) print(count("hi"))
Show answer
The dict {} is created once at definition time and stored as the default, so both calls mutate the same dict. The second call prints {'hi': 2}. Fix it by using seen=None in the signature and adding if seen is None: seen = {} at the top of the body.