General decorator to wrap try except in python?

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

    Extending @iruvar answer - starting with Python 3.4 there is an existing context manager for this in Python standard lib: https://docs.python.org/3/library/contextlib.html#contextlib.suppress

    from contextlib import suppress
    
    with suppress(FileNotFoundError):
        os.remove('somefile.tmp')
    
    with suppress(FileNotFoundError):
        os.remove('someotherfile.tmp')
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题