我可以将异常作为参数传递给python中的函数吗?

Har*_*non 2 python decorator python-decorators

我是python的新手.我正在尝试创建一个重试装饰器,当应用于函数时,将继续重试,直到满足某些条件(为简单起见,重试10次).

def retry():
    def wrapper(func):
        for i in range(0,10):
            try:
                func()
                break
            except:
               continue
    return wrapper
Run Code Online (Sandbox Code Playgroud)

现在,这将重试任何异常.如何更改它以使其在特定异常上重试.例如,我想用它像:

@retry(ValueError, AbcError)
def myfunc():
    //do something
Run Code Online (Sandbox Code Playgroud)

我只想myfunc重新尝试ValueError或者重试AbcError.

Mar*_*ers 8

您可以提供块tuple的例外except ..以捕获:

from functools import wraps

def retry(*exceptions, **params):
    if not exceptions:
        exceptions = (Exception,)
    tries = params.get('tries', 10)

    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kw):
            for i in range(tries):
                try:
                    return func(*args, **kw)
                except exceptions:
                    pass
        return wrapper
    return decorator
Run Code Online (Sandbox Code Playgroud)

catch-all *exceptions参数将始终生成元组.我也添加了一个tries关键字,因此您也可以配置重试次数:

@retry(ValueError, TypeError, tries=20)
def foo():
    pass
Run Code Online (Sandbox Code Playgroud)

演示:

>>> @retry(NameError, tries=3)
... def foo():
...     print 'Futzing the foo!'
...     bar
... 
>>> foo()
Futzing the foo!
Futzing the foo!
Futzing the foo!
Run Code Online (Sandbox Code Playgroud)