Why does a default list keep items from earlier calls?
Question
A helper records events in a list. Callers often omit bucket to start fresh, expecting a one-item list each time. Instead, two separate calls end up sharing the same list.
- Predict the three lines the starter prints and explain why
firstandsecondshare one list. - Fix
add_eventso omittingbucketcreates a new list each call, while passing an explicit empty listshared = []still appends intoshared.
def add_event(name, bucket=[]): bucket.append(name) return bucket first = add_event("login") second = add_event("logout") print(first) print(second) print(first is second)
Show hints (3)
- "WHEN DEFAULTS RUN"
Python evaluates
bucket=[]only once, whendef add_eventruns, not on each call. Checkadd_event.__defaults__. - "USE A SENTINEL"
Set the default to
Noneand create a fresh list inside the function body wheneverbucketis omitted. - "EMPTY LIST CHECK"
Test
if bucket is None:rather thanbucket = bucket or []. An explicit empty list[]is falsy.
Show checked explanation
The starter prints ['login', 'logout'], ['login', 'logout'], and True. Python evaluates bucket=[] once at def time and stores that single list in add_event.__defaults__. Fix it by defaulting to None and assigning bucket = [] only when bucket is None.
def add_event(name, bucket=None): if bucket is None: bucket = [] bucket.append(name) return bucket first = add_event("login") second = add_event("logout") shared = [] third = add_event("ping", shared) print(first) print(second) print(first is second) print(shared, third is shared)
['login'] ['logout'] False ['ping'] True
Code run on CPython 3.12.10 against the starter bug, fixed solution, and dataclass edge cases above. Checked by an editor other than the author.
Walkthrough
In Python, def is an executable statement. When it runs, Python evaluates every default expression once and saves the resulting tuple on add_event.__defaults__. Each call that omits bucket reuses that exact list object.
| Step | add_event.__defaults__ | first | second |
|---|---|---|---|
def add_event | ([],) | not set | not set |
first = add_event("login") | (['login'],) | ['login'] | not set |
second = add_event("logout") | (['login', 'logout'],) | ['login', 'logout'] | ['login', 'logout'] |
Because first and second point to the same list in __defaults__, first is second is True. Even first changes when the second call runs.
Setting bucket=None fixes the bug because None is immutable. Inside the body, if bucket is None: runs on every call and builds a fresh list only when the caller omitted bucket.
Do not write bucket = bucket or []. An empty list [] is falsy in Python. Passing shared = [] would skip shared, build a brand-new list, and leave shared empty. Checking is None keeps the caller's list intact.
For classes using dataclasses, Python blocks events: list[str] = [] with a ValueError. Use field(default_factory=list) so each instance gets its own list:
from dataclasses import dataclass, field @dataclass class AuditLog: events: list[str] = field(default_factory=list)
This bug also differs from shallow copying and closure late binding. Nobody copied a dict here, and closures read variables late when called. Default arguments evaluate early, at def time.
Common mistakes
- Writing
bucket = bucket or []. Because[]is falsy, passing an empty caller listshared = []silently creates a new list and leavessharedunchanged. - Using
datetime.now()oruuid.uuid4()as a default value. Python calls it once at import time, so every later call gets the same startup timestamp or ID. - Putting
events = []directly on a plain class body instead ofself.events = []in__init__. Every instance then appends to one shared class list. - Blaming shallow copying. Shallow copying shares nested objects between two containers, whereas here Python created only one list in
__defaults__before any call ran.
Follow-up questions
- "What if
Noneis a valid value that a caller might pass on purpose?" Define a private sentinel object at module level:_MISSING = object(). Setdef record(value=_MISSING):and checkif value is _MISSING:. No caller can pass_MISSINGby accident, sorecord(None)preservesNonewhilerecord()builds the fresh default. - "How does this compare to closure late binding in a loop?" They happen at opposite times. A closure reads its outer loop variable late, when the function is called, so every callback sees the final loop value. A default argument runs early, once at
deftime. Early evaluation helps freeze an integer inlambda i=i: i, but shares a mutable list across calls. - "Is a mutable default argument ever a good idea?" Rarely, except for a tiny private cache such as
_cache={}inside a helper. In production code, preferfunctools.lru_cacheor an explicit cache object. Hidden state inside__defaults__leaks across unit tests and appears inhelp()andinspect.signature().
What a strong answer covers
Explains that defaults evaluate once at def time and live in __defaults__. Fixes it with None and is None, warns why bucket or [] breaks explicit empty lists, and names field(default_factory=list) for dataclasses.
Open in interactive practice deck →