Code Demo · Python · Retry and Backoff
python-3
By anonymouspython-3
import time
from typing import Callable, Optional, TypeVar
T = TypeVar("T")
def retry(operation: Callable[[], T], attempts: int = 4, base_delay: float = 0.05) -> T:
last_error: Optional[RuntimeError] = None
for attempt in range(attempts):
try:
return operation()
except RuntimeError as error:
last_error = error
if attempt == attempts - 1:
raise
time.sleep(base_delay * (2 ** attempt))
if last_error is not None:
raise last_error
raise RuntimeError("retry exhausted")
calls = 0
def flaky_operation() -> str:
global calls
calls += 1
if calls < 3:
raise RuntimeError("temporary failure")
return "recovered"
print(retry(flaky_operation), "after", calls, "attempts")794 characters28 lines< 2.3 KB