Skip to content

Instantly share code, notes, and snippets.

@hoffmann
Created July 10, 2010 10:10
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save hoffmann/470611 to your computer and use it in GitHub Desktop.
Save hoffmann/470611 to your computer and use it in GitHub Desktop.
import time
class Retry(object):
default_exceptions = (Exception)
def __init__(self, tries, exceptions=None, delay=0):
"""
Decorator for retrying function if exception occurs
tries -- num tries
exceptions -- exceptions to catch
delay -- wait between retries
"""
self.tries = tries
if exceptions is None:
exceptions = Retry.default_exceptions
self.exceptions = exceptions
self.delay = delay
def __call__(self, f):
def fn(*args, **kwargs):
exception = None
for _ 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 tries, raise last exception
raise exception
return fn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment