Skip to content

Instantly share code, notes, and snippets.

@treo
Forked from hoffmann/retry_decorator.py
Created December 4, 2010 17:04
Show Gist options
  • Save treo/728327 to your computer and use it in GitHub Desktop.
Save treo/728327 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
from functools import wraps
import time
def retry(tries, exceptions=None, delay=0):
"""
Decorator for retrying a function if exception occurs
tries -- num tries
exceptions -- exceptions to catch
delay -- wait between retries
"""
exceptions_ = exceptions or (Exception, )
def _retry(fn):
@wraps(fn)
def __retry(*args, **kwargs):
for _ in xrange(tries+1):
try:
return fn(*args, **kwargs)
except exceptions_, e:
print "Retry, exception:" + str(e)
time.sleep(delay)
#if no success after tries raise last exception
raise
return __retry
return _retry
if __name__ == '__main__':
@retry(1)
def fail():
raise Exception("Oh woe is me")
@retry(42)
def no_fail():
print "I work"
print "This will not fail"
no_fail()
print "--"
print "The next test is going to fail"
fail()
@treo
Copy link
Author

treo commented Dec 4, 2010

The script will produce this output when run:

This will not fail
I work
--
The next test is going to fail
Retry, exception:Oh woe is me
Retry, exception:Oh woe is me
Traceback (most recent call last):
  File "retry_decorator.py", line 42, in <module>
    fail()
  File "retry_decorator.py", line 19, in __retry
    return fn(*args, **kwargs)
  File "retry_decorator.py", line 31, in fail
    raise Exception("Oh woe is me")
Exception: Oh woe is me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment