Python 3.7+dataclassesfunction
dataclasses.replace()
copying
Creates a new dataclass instance from an existing one, replacing the fields given.
Syntax
dataclasses.replace(obj, **changes)
replace() re-runs __init__ (and __post_init__) rather than copying the object field by field: fields declared with init=False cannot be passed and are recomputed instead of carried over. The copy is shallow, so nested lists and dicts stay shared with the original. For frozen dataclasses this is the sanctioned way to "change" a field, which is why such classes rarely need setters.
Examples
from dataclasses import dataclass, replace
@dataclass
class Point:
x: int; y: int
p = Point(1, 2)
p2 = replace(p, x=10)
p2 # → Point(x=10, y=2)
p # → Point(x=1, y=2)
replace(p, x=0, y=0) # → Point(x=0, y=0)
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy