General decorator to wrap try except in python?

后端 未结 8 1714
庸人自扰
庸人自扰 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:41

    There are lots of good answers here, but I didn't see any that address the question of whether you can accomplish this via decorators.

    The short answer is "no," at least not without structural changes to your code. Decorators operate at the function level, not on individual statements. Therefore, in order to use decorators, you would need to move each of the statements to be decorated into its own function.

    But note that you can't just put the assignment itself inside the decorated function. You need to return the rhs expression (the value to be assigned) from the decorated function, then do the assignment outside.

    To put this in terms of your example code, one might write code with the following pattern:

    @return_on_failure('')
    def computeA():
        item['a'] = myobject.get('key').METHOD_THAT_DOESNT_EXIST()
    
    item["a"] = computeA()
    

    return_on_failure could be something like:

    def return_on_failure(value):
      def decorate(f):
        def applicator(*args, **kwargs):
          try:
             f(*args,**kwargs)
          except:
             print('Error')
    
        return applicator
    
      return decorate
    

提交回复
热议问题