【问题标题】:How to use @retry with keyword arguments AND pass a function如何将@retry 与关键字参数一起使用并传递函数
【发布时间】:2015-02-22 03:46:14
【问题描述】:

我正在使用重试 (pip install retrying) 包。

我有这样的功能 -

from retrying import retry
from random import randint

def a():
    number = randint(0, 10)

    if number > 0:
        print number
        raise Exception("Some exception")
    else:
        return number

# Case 1
a = retry(a)  # This works as expected - i.e. execs until I get a 0
print a()

# Case 2
a = retry(a, stop_max_attempt_number=3)
print a()

在情况 2 中,stop_max_attempt_number 无效。是否有不同的方法来传递函数,AND 关键字 arg?

我的用例是我想要仅在需要时装饰函数,因此将@retry(stop_max_attempt_number=3) 放在def a() 之前的典型用法不是我需要的。

【问题讨论】:

    标签: python decorator python-decorators


    【解决方案1】:

    retry 是一个装饰器,既可以不带参数也可以带参数使用。如果您给它参数,它将充当装饰器 factory 并返回实际的装饰器。调用返回的装饰器:

    a = retry(stop_max_attempt_number=3)(a)
    

    因为这相当于使用retry() 作为装饰器:

    @retry(stop_max_attempt_number=3)
    def a():
        # ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-01
      • 1970-01-01
      • 2018-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-24
      • 2021-07-08
      相关资源
      最近更新 更多