簡體   English   中英

Python 用動態參數重試

[英]Python retry with dynamic parameters

retryingtenacity python 庫中嘗試過此方法無濟於事。

重試通常與裝飾器一起使用,例如下面的元代碼所示:

class FooBar:

   @retry(attempts=3)
   def dosomething():
      ...

我希望可以在 class 上配置重試參數

class FooBar:
   def __init__(retries=0):
       self.retries = retries

   @retry(attempts=self.retries)
   def dosomething():
      ...

顯然這會中斷,因為裝飾器無法訪問 object 屬性(即無法訪問self )。 所以認為這會起作用:

def dosomething():
   with retry(attempts=self.retries):
       ...

但是兩個庫都不允許在with塊中調用重試

>  with retry():
E  AttributeError: __enter__

用動態參數包裝重試邏輯的首選方法是什么?

您不需要使用帶有@語法的 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)

嵌套的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM