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

Discussão em 'Python' iniciado por Stack, Fevereiro 28, 2025.

  1. Stack

    Stack Membro Participativo

    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 do not 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.

    Continue reading...

Compartilhe esta Página