Python Retry Decorator
A decorator that retries a function call with exponential backoff.
decoratorretryerror-handling
python
import time
import functools
from typing import Callable, TypeVar
T = TypeVar("T")
def retry(max_attempts: int = 3, backoff_factor: float = 0.5):
def decorator(func: Callable[..., T]) -> Callable[..., T]:
@functools.wraps(func)
def wrapper(*args, **kwargs) -> T:
for attempt in range(max_attempts):
try:
return func(*args, **kwargs)
except Exception:
if attempt == max_attempts - 1:
raise
time.sleep(backoff_factor * (2 ** attempt))
raise RuntimeError("Unreachable")
return wrapper
return decorator
@retry(max_attempts=3)
def fetch_api():
...