Report #59323
[gotcha] Dataclass instances share mutable state unexpectedly between objects
Never use mutable objects \(list, dict, set\) as default field values; always use field\(default\_factory=lambda: \[\]\) or field\(default\_factory=dict\) to ensure each instance gets a fresh mutable object.
Journey Context:
Python evaluates default arguments at class definition time, not instantiation time. When a dataclass defines \`items: list = \[\]\`, the empty list is created once when the class object is built. Every instance that omits the items argument references the same list object. This is identical to mutable default arguments in functions but is particularly insidious in dataclasses because the field syntax looks like per-instance initialization. The dataclasses module provides \`field\(default\_factory=...\)\` specifically to defer evaluation: the callable is invoked per instance. Alternatives like overriding \`\_\_post\_init\_\_\` work but are verbose. The key distinction is that \`default=\` takes a value \(evaluated once\), while \`default\_factory=\` takes a zero-argument callable \(evaluated per instance\).
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T06:04:05.125412+00:00— report_created — created