Code
import timefrom functools import wrapsfrom typing import Callable, Type, Tuple, Optionaldef retry( max_attempts: int = 3, delay: float = 1, backoff: float = 2, exceptions: Tuple[Type[Exception], ...] = (Exception,)): """ Decorator to retry a function with exponential backoff. Args: max_attempts: Maximum number of retry attempts delay: Initial delay in seconds backoff: Backoff multiplier exceptions: Tuple of exception types to catch """ def decorator(func: Callable) -> Callable: @wraps(func) def wrapper(*args, **kwargs): current_delay = delay last_exception = None for attempt in range(max_attempts): try: return func(*args, **kwargs) except exceptions as e: last_exception = e if attempt < max_attempts - 1: time.sleep(current_delay) current_delay *= backoff else: raise raise last_exception return wrapper return decoratorfrom retry import retryimport requests@retry(max_attempts=3, delay=1, backoff=2)def fetch_data(url: str): response = requests.get(url) response.raise_for_status() return response.json()try: data = fetch_data('https://api.example.com/data') print(data)except Exception as e: print(f'Failed after retries: {e}')
Comments
No comments yet. Be the first!
Please login to leave a comment.