import time import random from functools import wraps Wormax Io Script Apr 2026
@retry(max_retries=3, delay=1, allowed_exceptions=(ConnectionError,)) def unstable_network_call(): global call_count call_count += 1 print(f"Calling network... (Count: {call_count})") # Simulate success on the 3rd try if call_count < 3: raise ConnectionError("Simulated network failure") return "Success!" Kutty Movies Com 2023 Tamil High Quality
# Simulating an unreliable function call_count = 0
def retry(max_retries=3, delay=1, backoff=2, allowed_exceptions=(Exception,)): """ A decorator that retries a function if it fails. Args: max_retries (int): Maximum number of retries. delay (float): Initial delay between retries in seconds. backoff (float): Multiplier for the delay after each retry. allowed_exceptions (tuple): Exceptions that trigger a retry. """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): current_delay = delay for attempt in range(max_retries + 1): try: return func(*args, **kwargs) except allowed_exceptions as e: if attempt == max_retries: print(f"Function {func.__name__} failed after {max_retries} retries.") raise e # Add jitter to prevent thundering herd problem jitter = random.uniform(0.5, 1.5) sleep_time = current_delay * jitter print(f"Retrying {func.__name__} in {sleep_time:.2f} seconds... (Attempt {attempt + 1}/{max_retries})") time.sleep(sleep_time) # Increase delay for next attempt current_delay *= backoff return wrapper return decorator
This utility allows you to automatically retry a function if it raises an exception, with customizable wait times and retry limits. It's incredibly useful for web scraping, API calls, or database connections.
# --- Example Usage ---