[英]Python retry with dynamic parameters
Tried this in the retrying and tenacity python libraries to no avail.在retrying和tenacity python 库中尝试过此方法无济于事。
Retries are typically used with a decorator, for example as shown in metacode below:重试通常与装饰器一起使用,例如下面的元代码所示:
class FooBar:
@retry(attempts=3)
def dosomething():
...
I want the retry parameters to be configurable on the class我希望可以在 class 上配置重试参数
class FooBar:
def __init__(retries=0):
self.retries = retries
@retry(attempts=self.retries)
def dosomething():
...
Obviously this will break because the decorator cannot accedss object attributes (ie. cannot access self
).显然这会中断,因为装饰器无法访问 object 属性(即无法访问
self
)。 So figured this would work:所以认为这会起作用:
def dosomething():
with retry(attempts=self.retries):
...
But neither library allows for retry to be called in a with
block但是两个库都不允许在
with
块中调用重试
> with retry():
E AttributeError: __enter__
What is the preferred way to wrap retry logic with dynamic parameters?用动态参数包装重试逻辑的首选方法是什么?
You needn't use deorators with the @
syntax - they can also be used as functions.您不需要使用带有
@
语法的 deorators - 它们也可以用作函数。
from tenacity import retry, stop_after_attempt
class CustomClass:
def __init__(self, retries):
decorator = retry(stop=stop_after_attempt(retries), reraise=True)
self.method_with_retry = decorator(self.method)
def method(self, x):
print('Trying...')
if x % 2:
raise ValueError
return x
CustomClass(3).method_with_retry(11)
Nested function can help this:嵌套的 function 可以帮助解决这个问题:
class FooBar:
def __init__(retries=0):
self.retries = retries
def dosomething():
@retry(attempts=self.retries)
def _dosomething():
...
return _dosomething()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.