Retry Decorator With Backoff

Decorate a function so transient exceptions are retried a fixed number of times with growing delay, keeping call sites free of retry plumbing.

PythonResilience

Code

pythonsnippet
31 lines
import functools
import time
from typing import Callable, Tuple, Type, TypeVar

T = TypeVar("T")


def retry(
    attempts: int = 3,
    delay: float = 0.1,
    backoff: float = 2.0,
    exceptions: Tuple[Type[BaseException], ...] = (Exception,),
) -> Callable[[Callable[..., T]], Callable[..., T]]:
    def decorator(func: Callable[..., T]) -> Callable[..., T]:
        @functools.wraps(func)
        def wrapper(*args, **kwargs) -> T:
            remaining = attempts
            wait = delay
            while True:
                try:
                    return func(*args, **kwargs)
                except exceptions:
                    remaining -= 1
                    if remaining <= 0:
                        raise
                    time.sleep(wait)
                    wait *= backoff

        return wrapper

    return decorator

Inside the snippet

The working surface is the functions retry, decorator and wrapper — everything else is wiring.

The one repetition in this snippet is the loop while True. time appears at a raise inside an except handler — it fires only while that failure type is already being handled.

Points of care

  • The guard remaining <= 0 short-circuits the flow with an early raise when its condition holds.

Putting it to use

The main signature reads def retry( attempts: int = 3, delay: float = 0.1, backoff: float = 2.0, exceptions: Tuple[Type[BaseExceptio…

The surface worth importing is retry; the helpers around it are private to the snippet.

Core lines

def wrapper(*args, **kwargs) -> T:
    remaining = attempts
    wait = delay
    while True:
        try:
            return func(*args, **kwargs)
        except exceptions:
            remaining -= 1
            if remaining <= 0:
                raise
            time.sleep(wait)
            wait *= backoff

Interactive Tools for This Topic

FAQ

When is the exception raised?
Inside an `except` handler — the `time` fires only while that failure type is already being handled, not on its own trigger.
Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `retry`, `decorator`, `wrapper` at load time.