我想使用Tenacity Python库作为它的@retry装饰器。但是,我想在每次重试时使用不同的参数调用我的函数,但不确定如何指定。
我的函数定义如下所示:
from tenacity import retry, retry_if_exception_type, stop_after_attempt
class CustomError(Exception):
pass
@retry(retry=retry_if_exception_type(CustomError), stop=stop_after_attempt(2))
def my_function(my_param):
result = do_some_business_logic(my_param)
if not result:
if my_param == 1:
raise CustomError()
else:
raise ValueError()
# first invoke the function with my_param=1, then retry with my_param=2
my_function(1)这稍微简化了一点,但是我的想法是,当我第一次调用函数时,我将传入1作为第一个参数。在重试时,我希望它将此值更改为2。这可以通过坚韧的@retry装饰器来实现吗?也许是通过回调?
发布于 2019-01-19 02:19:50
最简单的方法可能是传入一个可产生所需值的可迭代对象,而不是一个整数。例如:
@retry(retry=retry_if_exception_type(CustomError), stop=stop_after_attempt(2))
def my_function(my_iter):
my_param = next(my_iter)
result = do_some_business_logic(my_param)
if not result:
if my_param == 1:
raise CustomError()
else:
raise ValueError()
my_function(iter([1, 2]))不过,这看起来确实像一个XY problem;也许有一种更好的方法可以使用坚韧来做您想做的事情。也许你应该发布一个关于重试的更一般的问题。
https://stackoverflow.com/questions/54259345
复制相似问题