Skip to content

Instantly share code, notes, and snippets.

@vmalloc
Created November 28, 2012 10:29
Show Gist options
  • Save vmalloc/4160364 to your computer and use it in GitHub Desktop.
Save vmalloc/4160364 to your computer and use it in GitHub Desktop.
Simple retries in Python
def retries(num_retries):
"""
Generates a sequence of retry attempt objects, helping you write nicer retry code:
Example usage:
for retry in retries(num_retries):
if not retry.first:
logging.debug("Retrying...")
try:
some_operation()
except PossibleException:
if retry.last:
raise
"""
return (RetryAttempt(i, num_retries) for i in xrange(num_retries))
class RetryAttempt(object):
def __init__(self, retry_number, total_retries):
super(RetryAttempt, self).__init__()
self.retry_number0 = retry_number
self.retry_number1 = retry_number + 1
self.first = (retry_number == 0)
self.last = (retry_number == total_retries - 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment