Python - what is the correct way to copy an object's attributes over to another?

Viewed 10238

I have two classes. They're almost identical, except for 2 attributes. I need to copy all the attributes over from one to the other, and I'm just wondering if there is a pattern or best practice, or if I should just basically do:

spam.attribute_one = foo.attribute_one
spam.attribute_two = foo.attribute_two

... and so on.

3 Answers

I used dictionary comprehension to iterate through the items and call setattr() for another object.

{k: setattr(object_to, k, v) for k, v in object_from.dict().items()}

Since I don't need any new dict, I have not assigned the return value to any variable.

Another way I tried is by using map()

dict(
    map(lambda item: (item[0], setattr(object_to, item[0], item[1])
                      ),
        object_from.dict().items()
        )
)

This might save a lot of loop iteration time.

Related