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

Question:

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.

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

Asked By: Ran Homri

||

Answers:

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 ]
Answered By: Ferret
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.