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.
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 ]
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.
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 ]