Sub topic 9
The mutable default argument pitfall
This chapter assumes you can define a function with def, give a parameter a default value, and use lists and dictionaries. You have seen that a default value lets callers leave an argument out. Here you will see why that feature misbehaves when the default is a list, a dictionary or a set.
The bug
Start with a function that appends an item to a list. The list defaults to an empty one.
def add_item_bad(item, items=[]):
items.append(item)
return items
print(add_item_bad(1)) # [1]
print(add_item_bad(2)) # [1, 2]The second call did not start from an empty list. It returned [1, 2], so the item from the first call was still there.
Why it happens
Python evaluates a default value once, when the def statement runs. It does not evaluate it again on each call. The function object stores that single value. Every call that leaves out the argument receives the same object.
A list is mutable, which means it can change in place. items.append(item) changes the one stored list, and the change is still there on the next call.
You can see the stored default on the function itself. The __defaults__ attribute holds it.
def add_item_bad(item, items=[]):
items.append(item)
return items
add_item_bad(1)
add_item_bad(2)
print(add_item_bad.__defaults__) # ([1, 2],)The fix: use None as the default
Use None as the default, then create a new list inside the function body. The body runs on every call, so each call gets a fresh list.
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item(1)) # [1]
print(add_item(2)) # [2]Use is None rather than if not items. An empty list that the caller passes in is falsy. With if not items, the function would silently replace the caller's list with a new one, and the caller would not see the appended item.
def add_item_wrong_check(item, items=None):
if not items:
items = []
items.append(item)
return items
mine = []
add_item_wrong_check(1, mine)
print(mine) # [] (the caller's list was ignored)
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
mine = []
add_item(1, mine)
print(mine) # [1]Which defaults are safe
The problem only appears when the default is mutable and the function changes it. Immutable defaults cannot change, so they are safe.
| Default value | Mutable? | Safe as a default? |
|---|---|---|
| `0`, `3.5`, `True` | No | Yes |
| `"text"` | No | Yes |
| `()` (empty tuple) | No | Yes |
| `None` | No | Yes |
| `[]`, `{}`, `set()` | Yes | No, use `None` |
The same bug appears with dictionaries and sets, and with any mutable object you build in the def line, such as a custom class instance.
Checking your own code
When you write a parameter with =, look at the value on the right. If it is a list, dictionary, set or object you construct, switch to None and build the value inside the function. Many linters flag this pattern, so turn that rule on in your editor.
Exercise
This function should return a dictionary with the given key set to the given value, starting from an empty dictionary when none is passed. Two separate calls to record("a", 1) and record("b", 2) currently return {"a": 1} and then {"a": 1, "b": 2}. Why, and how do you fix it?
def record(key, value, data={}):
data[key] = value
return data
Show answer
The default {} is created once when def runs, so every call that omits data changes the same dictionary. Use data=None as the default, then write if data is None: data = {} at the start of the body. Each call then gets its own new dictionary.
Exercise
Why is if items is None: better than if not items: when fixing a mutable default?
Show answer
not items is also true for an empty list that the caller passed in. The function would replace the caller's list with a new one, so the caller would not see the changes. is None replaces the value only when no argument was given.