General decorator to wrap try except in python?

后端 未结 8 1697
庸人自扰
庸人自扰 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 17:01

    It's very easy to achieve using configurable decorator.

    def get_decorator(errors=(Exception, ), default_value=''):
    
        def decorator(func):
    
            def new_func(*args, **kwargs):
                try:
                    return func(*args, **kwargs)
                except errors, e:
                    print "Got error! ", repr(e)
                    return default_value
    
            return new_func
    
        return decorator
    
    f = get_decorator((KeyError, NameError), default_value='default')
    a = {}
    
    @f
    def example1(a):
        return a['b']
    
    @f
    def example2(a):
        return doesnt_exist()
    
    print example1(a)
    print example2(a)
    

    Just pass to get_decorator tuples with error types which you want to silence and default value to return. Output will be

    Got error!  KeyError('b',)
    default
    Got error!  NameError("global name 'doesnt_exist' is not defined",)
    default
    

    Edit: Thanks to martineau i changed default value of errors to tuples with basic Exception to prevents errors.

提交回复
热议问题