General decorator to wrap try except in python?

后端 未结 8 1710
庸人自扰
庸人自扰 2020-12-12 16:25

I\'d interacting with a lot of deeply nested json I didn\'t write, and would like to make my python script more \'forgiving\' to invalid input. I find myself writing involve

8条回答
  •  醉酒成梦
    2020-12-12 16:48

    Why not just use cycle?

    for dst_key, src_key in (('a', 'key'), ('b', 'key2')):
        try:
            item[dst_key] = myobject.get(src_key).get('subkey')
        except Exception:  # or KeyError?
            item[dst_key] = ''
    

    Or if you wish write a little helper:

    def get_value(obj, key):
        try:
            return obj.get(key).get('subkey')
        except Exception:
            return ''
    

    Also you can combine both solutions if you have a few places where you need to get value and helper function would be more reasonable.

    Not sure that you actually need a decorator for your problem.

提交回复
热议问题