有没有和我的C#版本类似的优雅的Python可重用等待?

Is there an elegant Python reusable wait similar to my C# version?

我正在寻找这样的东西:

public static class Retry
{
   public static void Do(
       Action action,
       TimeSpan retryInterval,
       int retryCount = 3)
   {
       Do<object>(() => 
       {
           action();
           return null;
       }, retryInterval, retryCount);
   }

   public static T Do<T>(
       Func<T> action, 
       TimeSpan retryInterval,
       int retryCount = 3)
   {
       var exceptions = new List<Exception>();

       for (int retry = 0; retry < retryCount; retry++)
       {
          try
          { 
              if (retry > 0)
                  Thread.Sleep(retryInterval);
              return action();
          }
          catch (Exception ex)
          { 
              exceptions.Add(ex);
          }
       }

       throw new AggregateException(exceptions);
   }
}

来自这个post:Cleanest way to write retry logic?

我在 Python 中足够体面,知道如果有人提供一些提示,这会非常好。这是针对经常出现但很少得到妥善处理的测试代码。

您可以这样做,根据需要添加异常处理和其他附加功能:

def retry_fn(retry_count, delay, fn, *args, *kwargs):
    retry = True
    while retry and retry_count:
        retry_count -= 1
        success, results = fn(*args, **kwargs):
        if success or not retry_count:
            return results
        time.sleep(delay)