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

前端 未结 4 1677
终归单人心
终归单人心 2020-12-21 00:58

Let\'s assume you have defined a Python dataclass:

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


        
相关标签:
4条回答
  • 2020-12-21 01:19

    Another option which may be more elegant:

    import dataclasses
    
    marker_a = Marker(1.0, 2.0)
    marker_b = Marker(**dataclasses.asdict(marker_a))
    
    0 讨论(0)
  • 2020-12-21 01:26

    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.

    0 讨论(0)
  • 2020-12-21 01:27
    @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...

    0 讨论(0)
  • 2020-12-21 01:33

    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)
    
    0 讨论(0)
提交回复
热议问题