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

标签 python decorator python-decorators

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

def retry():
    def wrapper(func):
        for i in range(0,10):
            try:
                func()
                break
            except:
               continue
    return wrapper

现在将重试任何异常。我怎样才能改变它,让它重试特定的异常。例如,我想像这样使用它:

@retry(ValueError, AbcError)
def myfunc():
    //do something

我希望 myfunc 仅在抛出 ValueErrorAbcError 时重试。

最佳答案

您可以向 except .. block 提供异常的 tuple 以捕获:

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

包罗万象的*exceptions 参数总是会产生一个元组。我还添加了一个 tries 关键字,因此您也可以配置重试次数:

@retry(ValueError, TypeError, tries=20)
def foo():
    pass

演示:

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

关于python - 我可以将异常作为参数传递给 python 中的函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18101887/

相关文章:

python - 如何在Python中正确使用类装饰器链?

c# - ninject - 使用工厂模式将通用参数传递给装饰器链

python - 带有参数 : avoid parenthesis when no arguments 的装饰器

Python 理解正则表达式

从 mac 设置 python virtualenv - 在 linux 中使用它

python - View 中的 DJANGO 回调函数

python - 链接定义为类的装饰器?

Python 链接装饰器覆盖属性

python - 打印二叉树中从根开始的最长路径

Python 可继承函数