Skip to content

Instantly share code, notes, and snippets.

@arunshankerprasad
Last active December 28, 2015 07:49
Show Gist options
  • Save arunshankerprasad/7467378 to your computer and use it in GitHub Desktop.
Save arunshankerprasad/7467378 to your computer and use it in GitHub Desktop.
Decorator for retrying a function if an exception occurs
import time
class retry(object):
defaultexceptions = (Exception,)
def __init__(self, tries=1, exceptions=None, delay=0):
"""
Decorator for retrying a function if an exception occurs
@source: http://peter-hoffmann.com/2010/retry-decorator-python.html (updated to dynamically override tries)
Usage:
@retry(tries=4, exceptions=DownloadError, delay=1)
def asp():
# OR if you want to dynamically set the tries, add a keyword arg to your function like;
@retry(tries=1, exceptions=DownloadError, delay=1)
def asp(a, b):
pass
# When calling the function
asp(_tries=4)
@param: tries -- num tries
@param: exceptions -- exceptions to catch
@param: delay -- wait between retries
"""
self.tries = tries
if exceptions is None:
exceptions = Retry.defaultexceptions
self.exceptions = exceptions
self.delay = delay
def __call__(self, f):
def fn(*args, **kwargs):
# Dynamically override tries
if '_tries' in kwargs:
self.tries = kwargs.pop('_tries')
exception = None
for i in range(self.tries):
try:
return f(*args, **kwargs)
except self.exceptions, e:
print "Retry, exception: "+str(e)
time.sleep(self.delay)
exception = e
# If no success after defined tries, raise the last exception
raise exception
return fn
# Sample Usage
@retry(tries=4, exceptions=Exception)
def run(a, b):
print "Here", a, b
if a == 1:
raise Exception("a is 1")
if __name__ == '__main__':
run(0, 0)
run(1, 0, _tries=4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment