Skip to content

Instantly share code, notes, and snippets.

@wpcarro
Created October 29, 2019 17:37
Show Gist options
  • Save wpcarro/47fc423ca5733011e5433cc6009d9434 to your computer and use it in GitHub Desktop.
Save wpcarro/47fc423ca5733011e5433cc6009d9434 to your computer and use it in GitHub Desktop.
Simple retry loop in python with error simulation.
import random
def danger():
if random.choice([True, False]):
raise Exception
def main():
"""Attempt to loop `loop_count` times. Simulate random errors and create a
retry loop that attempts `retry_count` amount of retries."""
rs = retry_count = 3
li = loop_count = 5
while loop_count > 0 and retry_count > 0:
try:
danger()
print("No failure.")
loop_count -= 1
except Exception:
print("Failed! Retrying...")
retry_count -= 1
loop_count -= 1
continue
if loop_count > 0:
print("Failure. Loop count: {}/{}. Retry count: {}/{}.".format(
li - loop_count, li, rs - retry_count, rs))
else:
print("Success! Loop count: {}/{}. Retry count: {}/{}.".format(
li - loop_count, li, rs - retry_count, rs))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment