General decorator to wrap try except in python?

后端 未结 8 1713
庸人自扰
庸人自扰 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条回答
  •  旧时难觅i
    2020-12-12 16:52

    Since you're dealing with lots of broken code, it may be excusable to use eval in this case.

    def my_eval(code):
      try:
        return eval(code)
      except:  # Can catch more specific exceptions here.
        return ''
    

    Then wrap all your potentially broken statements:

    item['a'] = my_eval("""myobject.get('key').get('subkey')""")
    item['b'] = my_eval("""myobject.get('key2')""")
    item['c'] = my_eval("""func1(myobject)""")
    

提交回复
热议问题