retry.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import functools
  2. from time import perf_counter, sleep
  3. from typing import Callable, TypeVar
  4. from pip._vendor.typing_extensions import ParamSpec
  5. T = TypeVar("T")
  6. P = ParamSpec("P")
  7. def retry(
  8. wait: float, stop_after_delay: float
  9. ) -> Callable[[Callable[P, T]], Callable[P, T]]:
  10. """Decorator to automatically retry a function on error.
  11. If the function raises, the function is recalled with the same arguments
  12. until it returns or the time limit is reached. When the time limit is
  13. surpassed, the last exception raised is reraised.
  14. :param wait: The time to wait after an error before retrying, in seconds.
  15. :param stop_after_delay: The time limit after which retries will cease,
  16. in seconds.
  17. """
  18. def wrapper(func: Callable[P, T]) -> Callable[P, T]:
  19. @functools.wraps(func)
  20. def retry_wrapped(*args: P.args, **kwargs: P.kwargs) -> T:
  21. # The performance counter is monotonic on all platforms we care
  22. # about and has much better resolution than time.monotonic().
  23. start_time = perf_counter()
  24. while True:
  25. try:
  26. return func(*args, **kwargs)
  27. except Exception:
  28. if perf_counter() - start_time > stop_after_delay:
  29. raise
  30. sleep(wait)
  31. return retry_wrapped
  32. return wrapper