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