Skip to content

Instantly share code, notes, and snippets.

@akhilsreddy1
Forked from willcalderbank/retry.py
Created April 15, 2019 04:13
Show Gist options
  • Save akhilsreddy1/3b6f46022bdc4042c5faf76e4962c6f9 to your computer and use it in GitHub Desktop.
Save akhilsreddy1/3b6f46022bdc4042c5faf76e4962c6f9 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