Skip to content

Instantly share code, notes, and snippets.

@liaoyw
Created November 19, 2014 05:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liaoyw/fc192168884674c2475e to your computer and use it in GitHub Desktop.
Save liaoyw/fc192168884674c2475e to your computer and use it in GitHub Desktop.
retry function for `retry` times
import functools
import sys
def robust(expected, retry=3):
def wrapper(func):
@functools.wraps(func)
def robust_run(*args, **kw):
n = 0;
result = None
while n < retry:
try:
result = func(*args, **kw)
except Exception as e:
print >>sys.stderr, 'Robust run exception:', e
print 'Robust run(try=%d): %s with args %r %r: result=%r' % (n + 1, func.__name__, args, kw, result)
if result == expected:
break
n += 1
if n == retry:
print >>sys.stderr, 'Robust run(total_retry=%d): %s failed!' % (retry, func.__name__)
return result
return robust_run
return wrapper
"""
this is equal to:
test = robust(0)(test)
"""
@robust(0)
def test(n):
return n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment