Created
November 28, 2012 10:29
-
-
Save vmalloc/4160364 to your computer and use it in GitHub Desktop.
Simple retries in Python
This file contains 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
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