How to copy all properties of an object to another object, in Python?

Try destination.__dict__.update(source.__dict__).


If your class does not modify __getitem__ or __setitem__ for special attribute access all your attributes are stored in __dict__ so you can do:

 nobj.__dict__ = oobj.__dict__.copy()    # just a shallow copy

If you use python properties you should look at inspect.getmembers() and filter out the ones you want to copy.


If you have to do this, I guess the nicest way is to have a class attribute something like :

Class Copyable(object):
    copyable_attributes = ('an_attribute', 'another_attribute')

Then iterate them explicitly and use setattr(new, attr, getattr(old, attr)). I still believe it can be solved with a better design though, and don't recommend it.


At the risk of being modded down, is there a decent any use-case for this?

Unless we know exactly what it's for, we can't sensibly call it as "broken" as it seems.

Perhaps try this:

firstobject.an_attribute = secondobject.an_attribute
firstobject.another_attribute = secondobject.another_attribute

That's the sane way of copying things between instances.

Tags:

Python