Python The Mutable Default Trap
A mutable default is a list or dict written as a default value. The trap is that Python builds it once, not once per call.
The trap in action
Both calls share one list. The second call sees the first call's item.
def add(item, box=[]):
box.append(item)
return box
print(add("apple"))
print(add("pear"))The fix with None
None means no list was passed. The function then builds a fresh list each time.
def add(item, box=None):
if box is None:
box = []
box.append(item)
return box
print(add("apple"))
print(add("pear"))Safe defaults stay safe
A number default is rebuilt fresh each call. Nothing carries over.
def greet(name, times=1):
print(name * times)
greet("ha")
greet("ha")Example
def collect_errors(errors=None):
if errors is None:
errors = []
return errors
run_one = collect_errors()
run_one.append("missing file")
run_two = collect_errors()
run_two.append("bad number")
print("Run one:", run_one)
print("Run two:", run_two)Key points
- Mutable: a value a program can change, like a list or a dict
- Default values are built once, when the function is defined
- A list default is shared by every call that uses it
- Appends from one call stay in the list for the next call
- Use None as the default, then build a fresh list inside the function
- Use None for every mutable default, not only for lists
- Number and string defaults are safe. Only mutable defaults share.
In this example, collect_errors() gives each run its own list. The default is None, so the function builds a fresh list on every call. Run one holds only its own error. Run two holds only its own error. The two printouts prove the lists are separate: neither run sees the other's error.
Note
The trap hides well, because the first call always looks right.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Why does the list grow between calls in the trap version?