Last active
November 4, 2022 20:46
-
-
Save justinmklam/0ffb2dc0673c11abba69247b79094c50 to your computer and use it in GitHub Desktop.
Retry decorator with exponential backoff
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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