Back to results for “Operator Overloading”
Python › Dataclasses & NamedTuples

How would you use dataclasses.replace() to create a modified copy of an immutable (frozen) dataclass instance?

Advanced

Answer

dataclasses.replace(instance, **changes) creates a NEW instance of the same dataclass, copying all existing field values EXCEPT the ones you explicitly override via keyword arguments — essential for 'modifying' a frozen dataclass, since you can't mutate it directly.
from dataclasses import dataclass, replace

@dataclass(frozen=True)
class Point:
    x: int
    y: int

p1 = Point(1, 2)
p2 = replace(p1, y=99)  # creates a NEW Point, since p1 is frozen and can't be mutated
print(p1, p2)  # Point(x=1, y=2) Point(x=1, y=99)
Real-world example Producing a modified copy of an immutable configuration or value object without mutating the original.

Common follow-ups: How does dataclasses.replace() handle fields that were marked with init=False?