Python Exception Handling - Avoid Writing 30+ Attempts Other Than Blocks
I have a dictionary that is populated from xml. There are many key-value pairs in the dictionary. I have to fill in a custom object with values ββfrom this dictionary. I want to catch an exception, if one key is missing in the dictionary or the value is not the expected type, write down that key and continue execution. Is there a better way than surrounding each line with a try block to expect. To be specific, I want to avoid this syntax, it does what I need, but I am wondering if there is a more efficient solution:
try:
my_object.prop1 = dictionary['key1']
except Exception as e:
log.write('key1')
try:
my_object.prop2 = dictionary['key2']
except Exception as e:
log.write('key2')
try:
my_object.prop3 = dictionary['key3']
except Exception as e:
log.write('key3')
....
source to share
for key, prop in [('key1', 'prop1'), ('key2', 'prop2'), ('key3', 'prop3')]:
try:
setattr(my_object, prop, dictionary[key])
except KeyError:
log.write(key)
Note that I am also using KeyError
here; try to keep your caught exceptions as specific as possible. If prop1
can boost your own bugs, add this to the list of expected bugs.
source to share