,

Python – Retry Decorator in Python

Retry Decorator


import time

def retry(ExceptionToCheck, tries=4, delay=3, backoff=2):
    def deco_retry(f):
        def f_retry(*args, **kwargs):
            mtries, mdelay = tries, delay
            while mtries > 0:
                try:
                    return f(*args, **kwargs)
                except ExceptionToCheck, e:
                    print "%s, Retrying in %d seconds..." % (str(e), mdelay)
                    time.sleep(mdelay)
                    mtries -= 1
                    mdelay *= backoff
                    lastException = e
            raise lastException
        return f_retry # true decorator
    return deco_retry

Usage Example


@retry(Exception, tries=4)
def test_fail(text):
    raise Exception("Fail")

test_fail("it works!")u

References

1. Central repository of decorator code pieces: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry