Replace attributes in Data Class objects
I know the question is about dataclass
, but if you're using attr.s
instead then you can use attr.evolve
instead of dataclasses.replace
:
import attr
@attr.s(frozen=True)
class Foo:
x = attr.ib()
y = attr.ib()
foo = Foo(1, 2)
bar = attr.evolve(foo, y=3)
The dataclasses
module has a helper function for field replacement on instances (docs)
from dataclasses import replace
Usage differs from collections.namedtuple
, where the functionality was provided by a method on the generated type (Side note: namedtuple._replace
is documented/public API, using an underscore on the name was called a "regret" by the author, see link at end of answer).
>>> from dataclasses import dataclass, replace
>>> @dataclass
... class V:
... x: int
... y: int
...
>>> v = V(1, 2)
>>> v_ = replace(v, y=42)
>>> v
V(x=1, y=2)
>>> v_
V(x=1, y=42)
For more background of the design, see the PyCon 2018 talk - Dataclasses: The code generator to end all code generators. The replace
API is discussed in depth, along with other design differences between namedtuple
and dataclasses
, and some performance comparisons are shown.