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

别来无恙 提交于 2019-12-20 03:06:24

问题


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.


回答1:


I think that looping over the fields probably is the easiest way. All the other options I can think of involve creating a new object.

from dataclasses import fields

marker_a = Marker(5)
marker_b = Marker(0, 99)

for field in fields(Marker):
    setattr(marker_b, field.name, getattr(marker_a, field.name))

print(marker_b)  # Marker(a=5, b=1.0)



回答2:


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

marker_a = Marker(0.5)

marker_b = Marker(**m1.__dict__)

marker_b

# Marker(a=0.5, b=1.0)

If you didn't want to create a new instance, try this:

marker_a = Marker(1.0, 2.0)
marker_b = Marker(11.0, 12.0)

marker_b.__dict__ = marker_a.__dict__.copy()

# result: Marker(a=1.0, b=2.0)

Not sure whether that's considered a bad hack though...



来源:https://stackoverflow.com/questions/57962873/easiest-way-to-copy-all-fields-from-one-python-dataclass-instance-to-another-ins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!