Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 521
orokusaki Avatar asked Sep 29 '10 04:09

orokusaki


People also ask

What are the methods you know to copy an object in Python?

In Python, there are two ways to create copies : Deep copy. Shallow copy.

How can you copy an object in Python How do you make a deep copy?

To make a deep copy, use the deepcopy() function of the copy module. In a deep copy, copies are inserted instead of references to objects, so changing one does not change the other.


1 Answers

The code you give is correct and safe, avoiding "accidentally" binding attributes that should not be bound. If you favor automation over safety and correctness, though, you could use something like...:

def blindcopy(objfrom, objto):
    for n, v in inspect.getmembers(objfrom):
        setattr(objto, n, v);

However, I would not recommend it (for the reasons implied by the first para;-). OTOH, if you know the names of the attributes you want to copy, the following is just fine:

def copysome(objfrom, objto, names):
    for n in names:
        if hasattr(objfrom, n):
            v = getattr(objfrom, n)
            setattr(objto, n, v);

If you do this kind of thing often, having this code once in a "utilities" module can be a definite win for you!

like image 193
Alex Martelli Avatar answered Sep 22 '22 03:09

Alex Martelli