Created
December 5, 2019 16:31
-
-
Save curtis1000/3e59fc3b2861240dbf782a008137dd63 to your computer and use it in GitHub Desktop.
Python Retries
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
import time | |
# testing out the retry pattern described here: | |
# https://stackoverflow.com/questions/2083987/how-to-retry-after-exception/2083996#2083996 | |
tries = 5 | |
sleep = 1 | |
def throw_exception(): | |
return '2' + 2 | |
########################################## | |
print("\nTest case: complete failure\n") | |
for attempt in range(tries): | |
try: | |
print(f'Trying {attempt}...') | |
throw_exception() | |
except: | |
print('Failure, sleeping...') | |
time.sleep(sleep) | |
else: | |
print('Success, moving on!') | |
break | |
else: | |
print(f'We failed all {tries} tries') | |
########################################## | |
print("\nTest case: works on first try\n") | |
for attempt in range(tries): | |
try: | |
print(f'Trying {attempt}...') | |
except: | |
print('Failure, sleeping...') | |
time.sleep(sleep) | |
else: | |
print('Success, moving on!') | |
break | |
else: | |
print(f'We failed all {tries} tries') | |
########################################## | |
print("\nTest case: eventually works\n") | |
for attempt in range(tries): | |
try: | |
print(f'Trying {attempt}...') | |
if attempt < 2: | |
throw_exception() | |
except: | |
print('Failure, sleeping...') | |
time.sleep(sleep) | |
else: | |
print('Success, moving on!') | |
break | |
else: | |
print(f'We failed all {tries} tries') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment