github.com/hoffmann Peter Hoffmann on Stackoverflow @peterhoffmann on twitter Peter Hoffmann on Facebook Contact me per email Subscribe to Atom Feed

Peter Hoffmann

Software Engineer
prev page next page

Retry Decorator in Python

Posted on July 10, 2010
#python

The retry decorator reruns a funtion tries times if an exception occurs.

import time

class Retry(object):
    default_exceptions = (Exception,)
    def __init__(self, tries, exceptions=None, delay=0):
        """
        Decorator for retrying a 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

Usage:

>>> from retry_decorator import Retry
>>> @Retry(2)
... def fail_fn():
...     raise Exception("failed")
... 
>>> fail_fn()
Retry, exception: failed
Retry, exception: failed
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "retry_decorator.py", line 32, in fn
    raise exception
Exception: failed

gist.github.com Repository: http://gist.github.com/470611