Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python exception handling - avoid writing 30+ try except blocks

I have a dictionary which is populated from xml. Dictionary has a lot of key-value pairs. I have to populate a custom object with values from that dictionary. I want to catch exception if one key in dictionary is not present or the value is not the expected type, log which key and continue execution. Is there a better way than surrounding each line with try expect block. To be specific I want to avoid this syntax, it does what I need, but I'm 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')

....
like image 483
Mensur Avatar asked Mar 29 '26 15:03

Mensur


1 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)
like image 116
mike3996 Avatar answered Mar 31 '26 03:03

mike3996



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!