from __future__ import annotations import time import unittest from collections.abc import Callable from typing import ParamSpec, TypeVar P = ParamSpec("P") T = TypeVar("T") def retry_with_backoff( operation: Callable[P, T], *args: P.args, max_attempts: int = 3, initial_delay: float = 0.5, backoff_factor: float = 2.0, retry_on: tuple[type[Exception], ...] = (Exception,), sleep: Callable[[float], None] = time.sleep, **kwargs: P.kwargs, ) -> T: """Run an operation, retrying failures with exponential backoff.""" if max_attempts < 1: raise ValueError("max_attempts must be at least 1") if initial_delay < 0: raise ValueError("initial_delay cannot be negative") if backoff_factor < 1: raise ValueError("backoff_factor must be at least 1") delay = initial_delay for attempt in range(1, max_attempts + 1): try: return operation(*args, **kwargs) except retry_on: if attempt == max_attempts: raise # Wait progressively longer before each subsequent attempt. sleep(delay) delay *= backoff_factor raise RuntimeError("unreachable") class RetryWithBackoffTests(unittest.TestCase): def test_retries_until_success(self) -> None: attempts = 0 delays: list[float] = [] def flaky_operation() -> str: nonlocal attempts attempts += 1 if attempts < 3: raise OSError("temporary failure") return "success" result = retry_with_backoff( flaky_operation, max_attempts=4, initial_delay=0.25, backoff_factor=2, retry_on=(OSError,), sleep=delays.append, ) self.assertEqual(result, "success") self.assertEqual(attempts, 3) self.assertEqual(delays, [0.25, 0.5]) def test_raises_after_max_attempts(self) -> None: delays: list[float] = [] def always_fails() -> None: raise ValueError("permanent failure") with self.assertRaisesRegex(ValueError, "permanent failure"): retry_with_backoff( always_fails, max_attempts=3, initial_delay=1, retry_on=(ValueError,), sleep=delays.append, ) self.assertEqual(delays, [1, 2]) if __name__ == "__main__": unittest.main()