Easiest way to copy all fields from one dataclass instance to another?

The dataclasses.replace function returns a new copy of the object.
Without passing in any changes, it will return a copy with no modification:

>>> import dataclasses
>>> @dataclasses.dataclass
... class Dummy:
...     foo: int
...     bar: int
... 
>>> dummy = Dummy(1, 2)
>>> dummy_copy = dataclasses.replace(dummy)
>>> dummy_copy.foo = 5
>>> dummy
Dummy(foo=1, bar=2)
>>> dummy_copy
Dummy(foo=5, bar=2)

Note that this is a shallow copy.

Edit to address comments:

If a copy is undesirable, I would probably go with the following:

for key, value in dataclasses.asdict(dummy).items():
    setattr(some_obj, key, value)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)