Is there a library method to copy all the properties between two (already present) instances of the same class, in Python? I mean, something like Apache Commons' PropertyUtilsBean.copyProperties()
Thanks!
Is there a library method to copy all the properties between two (already present) instances of the same class, in Python? I mean, something like Apache Commons' PropertyUtilsBean.copyProperties()
Thanks!
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.
I know you down-modded copy, but I disagree. It's more clear to make another copy than to modify the existing in-place with dict manipulation, as others suggested (if you lose existing copy by reassigning the variable, it will get garbage-collected immediately). Python is not meant to be fast, it's meant to be readable (though I actually believe that copy() will be faster than the other methods).
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.
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.