使用Tenacity重试时是否可以动态更改传递给函数的参数?

时间:2019-01-18 18:05:20

标签: python

我想将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。可以使用Tenacity的@retry装饰器完成此操作吗?也许通过回调?

1 个答案:

答案 0 :(得分:0)

The easiest way to do this may be to pass in, not an integer, but an iterable object that yields the values you want. For example:

@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]))

This does look like an XY problem, though; there is probably a better way to use Tenacity to do what you want to do. Maybe you should post a more general question about retrying.