Last active
October 17, 2021 22:11
-
-
Save angstwad/e9c98bb7ef1fb5be1c9bf74dd81501e5 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
import time | |
import functools | |
def retry(wait, retries=3, reraise=True): | |
""" Decorator retries a function if an exception is raised during function | |
invocation, to an arbitrary limit. | |
:param wait: int, time in seconds to wait to try again | |
:param retries: int, number of times to retry function. If None, unlimited | |
retries. | |
:param reraise: bool, re-raises the last caught exception if true | |
""" | |
def inner(func): | |
@functools.wraps(func) | |
def wrapped(*args, **kwargs): | |
tries = 0 | |
while True: | |
try: | |
return func(*args, **kwargs) | |
except Exception as e: | |
tries += 1 | |
print "Caught: %s" % e | |
print "Sleeping %s." % wait | |
if tries <= retries or retries is None: | |
time.sleep(wait) | |
else: | |
break | |
if reraise: | |
raise | |
return wrapped | |
return inner |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment