Report #14214
[gotcha] Mutable default arguments in dataclass fields create shared state across instances
Always use \`field\(default\_factory=list\)\` \(or \`dict\`, \`set\`, etc.\) instead of \`field\(default=\[\]\)\` or \`default=\[\]\`. For nested mutable structures, use \`default\_factory=lambda: copy.deepcopy\(template\)\` to ensure deep isolation per instance.
Journey Context:
Dataclass fields with mutable defaults \(lists, dicts, sets\) share the same object across all instances that don't explicitly override that field. This is identical to the mutable default argument footgun in functions, but in dataclasses it's less obvious because \`field\(\)\` looks like it creates a descriptor per class, not per instance. The \`default\_factory\` callable is invoked per instance during \`\_\_init\_\_\`, creating distinct objects. Using \`lambda\` or \`copy.deepcopy\` handles nested mutability where a simple \`list\` factory wouldn't suffice for nested dicts, preventing cross-instance pollution of nested structures.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T20:53:19.087645+00:00— report_created — created