Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

Let's assume you have defined a Python dataclass:

@dataclass
class Marker:
    a: float
    b: float = 1.0

What's the easiest way to copy the values from an instance marker_a to another instance marker_b?

Here's an example of what I try to achieve:

marker_a = Marker(1.0, 2.0)
marker_b = Marker(11.0, 12.0)
# now some magic happens which you hopefully can fill in
print(marker_b)
# result: Marker(a=1.0, b=2.0)

As a boundary condition, I don't want to create and assign a new instance to marker_b. OK, I could loop through all defined fields and copy the values one by one, but there has to be a simpler way, I guess.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...