Skip to content

Instantly share code, notes, and snippets.

@kennethreitz
Forked from hoffmann/retry_decorator.py
Created December 7, 2010 15:50
Show Gist options
  • Save kennethreitz/731937 to your computer and use it in GitHub Desktop.
Save kennethreitz/731937 to your computer and use it in GitHub Desktop.

Revisions

  1. @hoffmann hoffmann revised this gist Jul 10, 2010. 1 changed file with 2 additions and 4 deletions.
    6 changes: 2 additions & 4 deletions retry_decorator.py
    Original file line number Diff line number Diff line change
    @@ -6,7 +6,7 @@ def __init__(self, tries, exceptions=None, delay=0):
    """
    Decorator for retrying function if exception occurs
    tries -- num retries (max runs = tries+1)
    tries -- num tries
    exceptions -- exceptions to catch
    delay -- wait between retries
    """
    @@ -18,15 +18,13 @@ def __init__(self, tries, exceptions=None, delay=0):

    def __call__(self, f):
    def fn(*args, **kwargs):
    tried = 0
    exception = None
    while tried <= self.tries:
    for _ in range(self.tries):
    try:
    return f(*args, **kwargs)
    except self.exceptions, e:
    print "Retry, exception: "+str(e)
    time.sleep(self.delay)
    tried += 1
    exception = e
    #if no success after tries, raise last exception
    raise exception
  2. @hoffmann hoffmann revised this gist Jul 10, 2010. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion retry_decorator.py
    Original file line number Diff line number Diff line change
    @@ -4,7 +4,7 @@ class Retry(object):
    default_exceptions = (Exception)
    def __init__(self, tries, exceptions=None, delay=0):
    """
    Decorator to for retrying function if exception occurs
    Decorator for retrying function if exception occurs
    tries -- num retries (max runs = tries+1)
    exceptions -- exceptions to catch
  3. @hoffmann hoffmann created this gist Jul 10, 2010.
    33 changes: 33 additions & 0 deletions retry_decorator.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    import time

    class Retry(object):
    default_exceptions = (Exception)
    def __init__(self, tries, exceptions=None, delay=0):
    """
    Decorator to for retrying function if exception occurs
    tries -- num retries (max runs = tries+1)
    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):
    tried = 0
    exception = None
    while tried <= self.tries:
    try:
    return f(*args, **kwargs)
    except self.exceptions, e:
    print "Retry, exception: "+str(e)
    time.sleep(self.delay)
    tried += 1
    exception = e
    #if no success after tries, raise last exception
    raise exception
    return fn