[英]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
会抛出ValueError
或AbcError
。
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.