SyntaxStudy
Sign Up
Python Advanced 5 min read

Retry Decorator

Retry Decorator

A retry decorator automatically re-runs a failing function a specified number of times, useful for network calls or flaky operations.

Example
import functools, time

def retry(times=3, delay=1):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(times):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    if attempt == times - 1:
                        raise
                    time.sleep(delay)
        return wrapper
    return decorator

@retry(times=3, delay=0.5)
def fetch_data():
    pass  # network call here
Pro Tip

Add exponential backoff (delay * 2**attempt) for production retry logic.