Skip to content

Instantly share code, notes, and snippets.

@blaxter
Created December 12, 2012 20:09
Show Gist options
  • Save blaxter/4271107 to your computer and use it in GitHub Desktop.
Save blaxter/4271107 to your computer and use it in GitHub Desktop.
retry decorator for python like the ruby one
class retry(bject):
"""
Decorator to retry function calls in case they raise exceptions
times - retries times (0 means only called once, like this decorator was
not used at all)
sleep - sleep time to wait aftera failure
debug - whether print to stdout info or not
"""
def __init__(self, times=1, sleep=0, debug=False):
self.times = times
self.sleep = sleep
self.debug = debug
def __call__(self, f):
def wrapper(*args, **kwargs):
exception = None
for i in range(self.times + 1):
try:
return f(*args, **kwargs)
except Exception, error:
exception = error
if self.debug:
print "Fail (%d): (%s)" % ((i + 1), str(error))
time.sleep(self.sleep)
raise exception
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment