import functools
import random
import time
def retry(attempts: int = 3, base: float = 0.2, on: tuple[type[BaseException], ...] = (Exception,)):
def decorator(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
for i in range(1, attempts + 1):
try:
return fn(*args, **kwargs)
except on as e:
if i == attempts:
raise
delay = base * (2 ** (i - 1))
time.sleep(delay + random.random() * delay)
return wrapper
return decorator
@retry(attempts=5, base=0.5, on=(ConnectionError, TimeoutError))
def fetch():
import requests
return requests.get("https://flaky.api/data", timeout=5).json()
Create a free account and build your private vault. Share publicly whenever you want.