Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding different attributes between two versions of an object (Python)

I have two instances of an object. one is the existing representation of the object as saved in a database and a new version created by some script.
I want to check which attributes of the new version differ from the attributes of the previous version loaded from the DB and update only those attributes.

My object is of the following form:

class Candidate:
    id: int
    job_history: List[JobHistoryItem]
    languages: List[LanguageItem]

Note that JobHistoryItem and LanguageItem are themselves objects with possibly list attributes and are not hashable.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want to have a list of Candidate’s attributes names that differ between the old and the new version of the candidate object.

>Solution :

You can use the == operator to compare the attributes of your classes and see which should be updated.

Example

updates = {}
if class.attribute == class0.attribute:
    updates["attribute"] = class0.attribute

class.update(updates)

Or to update them all seperately, something like this will work

[ class.update(x,y) for x,y in class0.items() if class[x] != y ]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading