Report #43695
[gotcha] Mutable default argument retains state between function calls
Use None as the default and initialize the mutable object inside the function: def f\(x=None\): if x is None: x = \[\].
Journey Context:
Python evaluates default arguments once at function definition time, not each call. If the default is a mutable object like a list or dict, mutations persist in the function object's \_\_defaults\_\_ attribute, leaking state between unrelated calls. This causes bugs where subsequent calls see leftover data from previous calls. The 'if x is None' idiom ensures a fresh mutable object per call while still allowing callers to pass explicit values. Using an empty tuple \(\) as a sentinel is safe but None is more idiomatic and readable.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T03:48:54.398822+00:00— report_created — created