【问题标题】:Can I dynamically change the arguments passed to a function when retrying with Tenacity?使用 Tenacity 重试时,我可以动态更改传递给函数的参数吗?
【发布时间】:2019-01-18 18:05:19
【问题描述】:

我想将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 装饰器完成吗?也许通过回调?

【问题讨论】:

    标签: python python-tenacity


    【解决方案1】:

    最简单的方法可能是传入,而不是整数,而是一个可迭代的对象,它产生你想要的值。例如:

    @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;可能有更好的方法来使用 Tenacity 来做你想做的事。也许你应该发布一个关于重试的更一般的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-04
      • 2014-02-02
      • 1970-01-01
      • 1970-01-01
      • 2011-02-20
      • 2023-03-15
      • 2010-12-15
      • 1970-01-01
      相关资源
      最近更新 更多