0

Given two instances of the same dataclass, how can I update the first one in-place with values from the second one?

i.e.

@dataclass
class Foo:
    a: str
    b: int

f1 = Foo("foo", 1)
f2 = Foo("bar", 2)

# Update in place, so that f1.a == f2.a, f1.b == f2.b and so on

Note: I do not want to simply set f1 = f2; I want to update f1 in place.

congusbongus
  • 13,359
  • 7
  • 71
  • 99

1 Answers1

1

Use dataclasses.fields to loop through all the attributes and set them one by one.

from dataclasses import fields

for f in fields(f2):
    setattr(f1, f.name, getattr(f2, f.name))
congusbongus
  • 13,359
  • 7
  • 71
  • 99