import time
from functools import wraps
from typing import Callable, TypeVar, ParamSpec
P = ParamSpec('P')
R = TypeVar('R')
def retry(
max_retries: int = 3,
delay_seconds: float = 1.0,
exponential_backoff: bool = True
) -> Callable[[Callable[P, R]], Callable[P, R]]:
"""
A decorator that retries the execution of a function upon raising an exception.
Args:
max_retries (int): The maximum number of retry attempts before raising the exception.
delay_seconds (float): The initial delay in seconds between retry attempts.
exponential_backoff (bool): If True, the delay doubles after each failed attempt.
Returns:
Callable[[Callable[P, R]], Callable[P, R]]: The decorated function.
"""
def decorator(func: Callable[P, R]) -> Callable[P, R]:
@wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
retries = 0
current_delay = delay_seconds
while True:
try:
return func(*args, **kwargs)
except Exception as e:
retries += 1
if retries > max_retries:
raise e
time.sleep(current_delay)
if exponential_backoff:
current_delay *= 2
return wrapper
return decorator