Skip to content

Instantly share code, notes, and snippets.

@justinmklam
Last active November 4, 2022 20:46
Show Gist options
  • Save justinmklam/0ffb2dc0673c11abba69247b79094c50 to your computer and use it in GitHub Desktop.
Save justinmklam/0ffb2dc0673c11abba69247b79094c50 to your computer and use it in GitHub Desktop.
Retry decorator with exponential backoff
import time
from functools import wraps
def retry(
ExceptionToCheck: Exception,
num_tries: int = 5,
delay_sec: int = 3,
backoff: int = 2,
):
"""Retry calling the decorated function using an exponential backoff.
Adapted from https://stackoverflow.com/a/52420132
"""
def deco_retry(f):
@wraps(f)
def f_retry(*args, **kwargs):
mtries, mdelay = num_tries, delay_sec
while mtries > 1:
try:
return f(*args, **kwargs)
except ExceptionToCheck:
time.sleep(mdelay)
mtries -= 1
mdelay *= backoff
return f(*args, **kwargs)
return f_retry # true decorator
return deco_retry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment