-
-
Save akhilsreddy1/3b6f46022bdc4042c5faf76e4962c6f9 to your computer and use it in GitHub Desktop.
Python retry decorator
This file contains 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
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