Report #90824
[gotcha] dataclasses.replace creates new identity for fields with default\_factory unexpectedly
When using dataclasses.replace\(\), explicitly provide values for fields that have default\_factory if the factory generates unique identities \(timestamps, UUIDs, counters\) and you want to preserve the original value. Do not assume replace\(\) preserves the original field value when default\_factory is present.
Journey Context:
dataclasses.replace\(\) is often used to create modified copies of immutable objects. When a field has no default, replace\(\) copies the value from the source object. However, if the field has a default\_factory, replace\(\) calls the factory to generate a new default value instead of copying the existing value from the source object. This is documented behavior but surprising: if your factory generates timestamps, UUIDs, or auto-incrementing IDs, replace\(\) will generate a new one instead of preserving the original object's ID. This breaks identity expectations in value objects and causes data inconsistency when using replace\(\) to create variations of objects. The workaround is to explicitly pass the field value to replace\(\): replace\(obj, id=obj.id\).
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T11:02:29.440328+00:00— report_created — created