Skip to content

Instantly share code, notes, and snippets.

@angstwad
Last active October 17, 2021 22:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angstwad/e9c98bb7ef1fb5be1c9bf74dd81501e5 to your computer and use it in GitHub Desktop.
Save angstwad/e9c98bb7ef1fb5be1c9bf74dd81501e5 to your computer and use it in GitHub Desktop.
Python Retry Decorator
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