Skip to content

Instantly share code, notes, and snippets.

@angstwad

angstwad/retry.py

Last active Feb 3, 2021
Embed
What would you like to do?
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