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')

....

      

+3


source to share


2 answers


Do it programmatically.



props_keys = {
    'prop1': 'key1'
    'prop2': 'key2',
    'prop3': 'key3'
}

for prop, key in props_keys.iteritems():
    try:
        setattr(myobj, prop, mydict[key])
    except KeyError:
        log(key)

      

+4


source


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.

+4


source







All Articles