Retry Decorator
Decorator for automatically retrying failed function calls with exponential backoff
Description
A decorator that automatically retries function calls when they raise exceptions. Supports exponential backoff, maximum retry attempts, and custom exception filtering.
Features
- Configurable retry attempts
- Exponential backoff delay
- Exception type filtering
- Custom retry conditions
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 decorator
from 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 to comment!
Please login to leave a comment.