Report #77611
[gotcha] Dataclass instances sharing mutable default values
Use dataclasses.field\(default\_factory=list\) \(or dict, set, etc.\) instead of default=\[\] or default=\{\} for mutable types. For nested structures, use a lambda or explicit factory function.
Journey Context:
Dataclasses look like they declare instance attributes, but class-level assignments define defaults. If you write x: List\[int\] = \[\], the empty list is created once at class definition time, not per instance. Every instance without an explicit x argument shares this single list. This is identical to the mutable default argument footgun in functions, but dataclasses make it look like 'clean' OOP syntax, lulling developers into thinking the default is per-instance. The field\(default\_factory=...\) ensures the callable is invoked per-instance, creating distinct mutable objects. This is also crucial for defaultdict, deque, or custom objects.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T12:52:17.867924+00:00— report_created — created