Skip to content

Retry a callable

Re-call a function with exponential backoff until it succeeds or hits a limit.

18th August 2026

from collections.abc import Callable
from time import sleep
from typing import TypeVar

T = TypeVar("T")


def retry(func: Callable[[], T], attempts: int = 5, delay: float = 1.0) -> T:
    last: BaseException | None = None
    current = delay
    for _ in range(attempts):
        try:
            return func()
        except Exception as exc:  # noqa: BLE001 — caller decides what to retry
            last = exc
            sleep(current)
            current *= 2
    assert last is not None
    raise last

Caveats

Not for functions that are not idempotent.