Skip to content

Instantly share code, notes, and snippets.

@cpdean
Created April 5, 2014 22:17
Show Gist options
  • Save cpdean/9998818 to your computer and use it in GitHub Desktop.
Save cpdean/9998818 to your computer and use it in GitHub Desktop.
import contextlib
def a_bad():
print "doing work"
raise IOError
def retry(n, f, e):
times = 0
while True:
try:
f()
except e:
if times > n:
raise
times += 1
continue
@contextlib.contextmanager
def context_retry(n, e):
times = 0
while True:
try:
yield
except e:
if times > n:
raise
times += 1
continue
if __name__ == '__main__':
try:
print "using funcs"
retry(2, a_bad, IOError)
except IOError:
print "finished func test"
try:
print "using context manager"
with context_retry(2, IOError):
a_bad()
except IOError:
print "finished context test"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment