Decorator Retry With Backoff
Apply retry with exponential backoff via a decorator for resilient function calls.
Code
import functools, time, random
def retry(max_attempts=3, base_delay=1):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(max_attempts):
try:
return func(*args, **kwargs)
except Exception as e:
if attempt == max_attempts - 1:
raise
delay = base_delay * 2**attempt + random.random()
time.sleep(delay)
return wrapper
return decoratorReport a problem with this exampleOpens a pre-filled issue on GitHub.