简体   繁体   English

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

[英]Can I pass an exception as an argument to a function in python?

I am new to python. 我是python的新手。 I am trying to create a retry decorator that, when applied to a function, will keep retrying until some criteria is met (for simplicity, say retry 10 times). 我正在尝试创建一个重试装饰器,当应用于函数时,将继续重试,直到满足某些条件(为简单起见,重试10次)。

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

Now that will retry on any exception. 现在,这将重试任何异常。 How can I change it such that it retries on specific exceptions. 如何更改它以使其在特定异常上重试。 eg, I want to use it like: 例如,我想用它像:

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

I want myfunc to be retried only of it throws ValueError or AbcError . 我希望只重试myfunc会抛出ValueErrorAbcError

You can supply a tuple of exceptions to the except .. block to catch: 您可以为except ..块提供一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

The catch-all *exceptions parameter will always result in a tuple. catch-all *exceptions参数将始终生成元组。 I've added a tries keyword as well, so you can configure the number of retries too: 我也添加了一个tries关键字,因此您也可以配置重试次数:

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

Demo: 演示:

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

class retry(object):
    def __init__(self, *exceptions):
        self.exceptions = exceptions

    def __call__(self, f):
        @wraps(f) # required to save the original context of the wrapped function
        def wrapped(*args, **kwargs):
            for i in range(0,10):
                try:
                    f(*args, **kwargs)
                except self.exceptions:
                    continue
        return wrapped

Usage: 用法:

@retry(ValueError, Exception)
def f():
    print('In f')
    raise ValueError


>>> f()
In f
In f
In f
In f
In f
In f
In f
In f
In f
In f

You can check the error class: 您可以检查错误类:

except Exception as e:
    for et in error_types: #(or args)
        if isinstance(e, et):
            continue
    raise e #re-raise

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Python中传递函数乘以常数作为参数 - How can I pass a function multiplied by a constant as argument in Python python - 如何在python pandas管道中将函数作为参数传递给参数 - How can I pass function as argument with parameter in python pandas pipe 我如何在python中的函数参数中传递实例属性 - How can i pass instance attribute in function argument in python 我可以将任意关键字参数传递给 function 吗? - Can I pass arbitrary keyword argument into a function? 如何将位置参数传递给 python 函数中的可选参数? - How can I pass a positional argument to an optional argument in python functions? 我可以在 Python 包装函数中只传递关键字参数的关键字名称吗? - Can I pass just the keyword name of a keyword argument in a Python wrapper function? Python bool()函数可以为无效参数引发异常吗? - Can the Python bool() function raise an exception for an invalid argument? 您可以将未解决的参数传递给 python 中的 class function 吗? - can you pass an unresolved argument to a class function in python? 在装饰器中,如何传递要装饰的函数作为参数? - In a decorator how can I pass the function I'm decorating as an argument? Python将函数名称作为参数传递 - Python pass function name as argument
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM