Created
December 12, 2012 20:09
-
-
Save blaxter/4271107 to your computer and use it in GitHub Desktop.
retry decorator for python like the ruby one
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class retry(bject): | |
""" | |
Decorator to retry function calls in case they raise exceptions | |
times - retries times (0 means only called once, like this decorator was | |
not used at all) | |
sleep - sleep time to wait aftera failure | |
debug - whether print to stdout info or not | |
""" | |
def __init__(self, times=1, sleep=0, debug=False): | |
self.times = times | |
self.sleep = sleep | |
self.debug = debug | |
def __call__(self, f): | |
def wrapper(*args, **kwargs): | |
exception = None | |
for i in range(self.times + 1): | |
try: | |
return f(*args, **kwargs) | |
except Exception, error: | |
exception = error | |
if self.debug: | |
print "Fail (%d): (%s)" % ((i + 1), str(error)) | |
time.sleep(self.sleep) | |
raise exception | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment