Report #42035
[gotcha] Dataclass instances share mutable default values \(e.g., lists\) between objects causing spooky action at a distance
Never use \`default=\[\]\` or \`default=\{\}\` in dataclass fields; always use \`field\(default\_factory=list\)\` or \`field\(default\_factory=dict\)\` for mutable types to ensure a new instance per object.
Journey Context:
Python evaluates default arguments at class definition time, not instantiation. In dataclasses, \`field\(default=\[\]\)\` stores a single list object as the default value in the class \`\_\_dict\_\_\`. Every instance that doesn't explicitly provide that field receives a reference to the exact same list, so appending to one instance's field modifies the shared list visible in all other instances. Using \`default\_factory\` defers creation to instantiation time, ensuring each object gets its own list. The alternative of setting the mutable object in \`\_\_post\_init\_\_\` works but is more verbose and error-prone because it requires remembering to handle every mutable field manually. This is the same footgun as mutable default arguments in functions, but specifically impacts dataclass users who assume the decorator handles defaults magically.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T01:01:39.491437+00:00— report_created — created