Skip to content
Advertisement

How to copy all attributes of one Python object to another?

I’ve got two classes, of which one inherits from the other:

JavaScript

I now create a Parent and change the attributes:

JavaScript

And from this point, I want to create a Child in which I want to copy all the attributes from the parent. I can of course do this like so:

JavaScript

The thing is that while developing, this class will grow to have a fairly large number of attributes, and I don’t constantly want to change the manual copying of the attributes into the child.

Is there a way to automatically take over the attributes of the parent object into a new child object? All tips are welcome!

[EDIT] Just to explain the WHY I want to do this. I use the Peewee ORM to interact with my DB. I now want to revision a table (meaning if a record gets updated, I want keep all previous versions). The way I intent to do that is by for example creating a Person class and a PersonRevision class which inherits from the Person class. I then override the peewee save() method to not only save the Person object, but also copy all attributes into a PersonRevision object and save that as well. Since I will never actually directly interact with the PersonRevision class I don’t need shadowing or any fancy stuff. I just want to copy the attributes and call the object its save() method.

Advertisement

Answer

The obvious solution is to use composition/delegation instead of inheritence:

JavaScript

This is of course assuming that you dont really want “copies” but “references to”. If you really want a copy it’s also possible but it can get tricky with mutable types:

JavaScript

If none of these solutions fit your needs, please explain your real use case – you may have an XY problem.

[edit] Bordering on a XY problem, indeed. The real question is: “How do I copy a peewee.Model‘s fields into another peewee.Model. peewee uses descriptors (peewee.FieldDescriptor) to control access to model’s fields, and store the fields names and definitions in the model’s _meta.fields dict, so the simplest solution is to iterate on the source model’s _meta.fields keys and use getattr / setattr:

JavaScript

NB : untested code, never used peewee, there’s possibly something better to do…

Advertisement