This has appeared several times recently, and I would like to deal with it better than I do: I have a number of attributes that I cross-reference between an object and a dictionary. If the value is different from them, I want to set the object.attribute attribute to the dictionary value ['attribute']. I also want to keep track of what has changed.
Now, my first thought is to simply use the if else statement for each attribute, but after writing a few of them, it is obvious that I am rewriting the same code again and again. There should be a DRY way to do this, where I point out only those parts that change every time, and then scroll through all the attributes.
There are 15 different attributes in the production code, but my example below just uses 2 for simplicity. I have some idea on how to do this in a smart way, but I miss the last step, actually setting the object.attribute attribute to the value of the dictionary ['attribute'].
# Simulated data setup - not under my control IRL class someClass: def __init__(self, name, version): self.name = name self.version = version objA = someClass('Test1','1.1') dictA = {'name':'Test1','revision':'1.2'}
The idea is that in this case, when I need to add another attribute, I can just update the list of checked attributes, and the rest of the code is already written. What is the pythonic way to accomplish this?
source share