Sub topic 9
The mutable default argument pitfall
This chapter assumes you can write functions with def, give parameters default values, and use lists and dictionaries. It also assumes you know that Python passes object references, so a function can change a list its caller owns. The chapter covers why one default value can leak state between calls, how to fix it, and where the same mistake appears outside lists.
The symptom
Here is a function that looks harmless:
def add_item_bad(item, items=[]):
items.append(item)
return items
print(add_item_bad(1)) # [1]
print(add_item_bad(2)) # [1, 2]
print(add_item_bad(3)) # [1, 2, 3]Each call omits items, so you would expect a fresh empty list every time. Instead, the list grows across calls. The function remembers earlier calls even though nothing global is involved.
Why it happens
A def statement is executed once, when Python reaches it. At that moment Python evaluates every default expression and stores the resulting objects on the function object. Calls do not re-evaluate them. When you omit an argument, the parameter is bound to the stored object.
For an integer or a string this is invisible, because those objects cannot change. A list can change, so every call that uses the default shares the same list. You can see the stored defaults in the __defaults__ attribute:
def collect(item, bucket=[]):
bucket.append(item)
return bucket
print(collect.__defaults__) # ([],)
first = collect("a")
second = collect("b")
print(collect.__defaults__) # (['a', 'b'],)
print(first is second) # True
print(first) # ['a', 'b']first and second are two names for the same list. The default object itself was modified, and that modification is what later calls see.
Which defaults are risky
The rule is not "lists are bad". The risk comes from defaults that are mutable and that the function body mutates.
| Default value | Mutable? | Safe as a default? |
|---|---|---|
| `0`, `1.5`, `True` | No | Yes |
| `"text"`, `b"bytes"` | No | Yes |
| `None` | No | Yes |
| `(1, 2)`, `frozenset()` | No | Yes |
| `[]`, `{}`, `set()` | Yes | No |
| `bytearray()`, `collections.deque()` | Yes | No |
| An instance of your own class | Usually | Usually no |
| `([],)` (a tuple holding a list) | Inner list is | No |
The last row matters because a tuple is immutable only at the top level. The list inside it can still change.
The standard fix: a None default
Use None as the default and create the real object inside the body. The body runs on every call, so each call gets a new object:
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]
mine = [10]
print(add_item(11, mine)) # [10, 11]
print(mine) # [10, 11]The last two lines show that the caller's own list is still mutated when passed in. That is ordinary argument passing, not the default-argument bug. Whether a function should mutate its input is a design question, covered in the chapter on side effects.
Test with `is None`, not truthiness
A tempting shortcut is if not items:. It breaks when the caller passes an empty list on purpose:
def add_item_falsy(item, items=None):
if not items:
items = []
items.append(item)
return items
mine = []
add_item_falsy(1, mine)
print(mine) # []An empty list is falsy, so the function discarded the caller's list and built a new one. The item went into a list nobody can see. Use is None so that only a missing argument triggers the replacement.
When None is a legitimate value
Sometimes None is a meaningful argument, so you cannot use it to mean "not provided". Create a private sentinel object instead. The sentinel is a unique object that no caller would pass by accident:
_MISSING = object()
def lookup(key, table, default=_MISSING):
if key in table:
return table[key]
if default is _MISSING:
raise KeyError(key)
return default
data = {"a": 1}
print(lookup("a", data)) # 1
print(lookup("b", data, None)) # NoneHere lookup("b", data) raises KeyError, while lookup("b", data, None) returns None. The built-in dict.pop behaves similarly. Because _MISSING is immutable in practice and is never modified, sharing it across calls is safe.
Evaluation time causes other bugs too
The root cause is "defaults are evaluated once", not "lists are shared". Any default whose value should differ per call has the same problem, even if it is immutable:
from datetime import datetime
def stamp_bad(when=datetime.now()):
return when
def stamp(when=None):
if when is None:
when = datetime.now()
return when
print(stamp_bad() == stamp_bad()) # Truestamp_bad returns the time the module was loaded, on every call, for the life of the program. A default such as time.time(), uuid.uuid4() or random.random() is frozen the same way. The None pattern fixes all of these.
Fragile "safe" code
Rebinding the parameter instead of mutating it does not touch the shared default:
def add_copy(item, items=[]):
items = items + [item]
return items
print(add_copy(1)) # [1]
print(add_copy(2)) # [2]items + [item] builds a new list and rebinds the local name, so the stored default stays empty. This works, but it is one edit from breaking. Changing the line to items += [item] mutates the list in place, because += on a list calls extend. The bug returns with no other change. Do not depend on this. A mutable default in a signature is a hazard for the next person who edits the function, so use None anyway.
When sharing is intentional
Occasionally you want one persistent object, for example a cache:
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 hides state in the signature, and callers can accidentally overwrite _cache by passing a second argument. Prefer functools.lru_cache or a module-level or class-level cache with a clear name. If you do rely on a shared default, leave a comment saying it is deliberate.
Related cases in classes and dataclasses
The same sharing happens when you write a mutable default in __init__:
class Basket:
def __init__(self, items=[]):
self.items = items
a = Basket()
b = Basket()
a.items.append("apple")
print(b.items) # ['apple']Both baskets hold the same list. The fix is the same: take items=None and assign self.items = [] when it is None.
Dataclasses guard against the problem. A mutable default for a field raises ValueError when the class is defined. Use default_factory, which is called on every instance creation:
from dataclasses import dataclass, field
@dataclass
class Cart:
items: list[str] = field(default_factory=list)
c1 = Cart()
c2 = Cart()
c1.items.append("pear")
print(c2.items) # []Catching it automatically
Linters flag this pattern. Ruff reports it as B006 (from flake8-bugbear), and Pylint reports W0102 (dangerous-default-value). Turning one of these on in your project catches the mistake before a test does.
Summary of the working model
- Defaults are evaluated once, when
defruns, and stored on the function. - A call that omits the argument binds the parameter to that stored object.
- Mutating the object changes what every later call sees.
- Use
Noneplus anis Nonecheck, a private sentinel whenNoneis a valid value, anddefault_factoryin dataclasses.
Exercise
What does this code print, and why? Then rewrite record so the second print shows ['b'].
def record(event, log=[]):
log.append(event)
return log
print(record("a"))
print(record("b"))
Show answer
It prints ['a'] and then ['a', 'b']. The default list is created once when def runs and is shared by every call that omits log, so the second call appends to the list the first call already modified. Fix:
def record(event, log=None):
if log is None:
log = []
log.append(event)
return log
Now each call that omits log creates a new list, so the second print shows ['b'].
Exercise
A function tag(name, tags=None) uses if not tags: tags = [] and then appends name to tags. A caller runs mine = [], then tag("x", mine), then prints mine. What is printed, and what single change to the function fixes the behavior?
Show answer
It prints []. An empty list is falsy, so not tags is true and the function replaces the caller's list with a new one. The item goes into the new list, not mine. Changing the test to if tags is None: fixes it, because only a missing argument triggers the replacement and the caller's empty list is used.
Exercise
Why does def log(msg, when=time.time()) record the same time on every call, even though time.time() returns an immutable float? Show the fix.
Show answer
Python evaluates time.time() once, when the def statement runs, and stores the resulting float as the default. Immutability does not help, because the problem is evaluation time, not mutation. Fix: use when=None and write if when is None: when = time.time() inside the body, so the call happens on every invocation.