Skip to content

Instantly share code, notes, and snippets.

@willcalderbank
Last active July 15, 2022 11:58
Show Gist options
  • Save willcalderbank/8397889 to your computer and use it in GitHub Desktop.
Save willcalderbank/8397889 to your computer and use it in GitHub Desktop.
Python retry decorator
def retry(times, exceptions):
"""
Retry Decorator
Retries the wrapped function/method `times` times if the exceptions listed
in ``exceptions`` are thrown
:param times: The number of times to repeat the wrapped function/method
:type times: Int
:param Exceptions: Lists of exceptions that trigger a retry attempt
:type Exceptions: Tuple of Exceptions
"""
def decorator(func):
def newfn(*args, **kwargs):
attempt = 0
while attempt < times:
try:
return func(*args, **kwargs)
except exceptions:
logger.info(
'Exception thrown when attempting to run %s, attempt '
'%d of %d' % (func, attempt, times),
exc_info=True
)
attempt += 1
return func(*args, **kwargs)
return newfn
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment