Skip to content

Instantly share code, notes, and snippets.

@scwood
Last active September 24, 2019 19:38
Show Gist options
  • Save scwood/9418f05417282da377a1e37cd0dae608 to your computer and use it in GitHub Desktop.
Save scwood/9418f05417282da377a1e37cd0dae608 to your computer and use it in GitHub Desktop.
Retry decorator in Python
import random
import time
# This is the decorator - it's essentially a function that takes in a function
# as a parameter and returns a modified version of it
def retry(func, max_attempts=4, initial_delay=1):
def wrapper(*args, **kwargs):
delay = initial_delay
attempt = 1
while True:
try:
return func(*args, **kwargs)
except Exception as e:
if attempt == max_attempts:
raise e
print(e)
print('Retrying in {} seconds'.format(delay))
time.sleep(delay)
delay *= 2
attempt += 1
return wrapper
# You can apply a decorator to a function with the @ syntax, this is just sugar
# for calling the decorator function and passing in the original function.
# e.g. you could do
# fail_half_the_time_with_retry = retry(fail_half_the_time)
# and it would be equivalent
@retry
def fail_half_the_time():
if random.randint(0, 1) == 0:
raise Exception('Failed!')
else:
return 'Success!'
# now if we call this decoratored version
print(fail_half_the_time())
# we should seee something like
# Failed!
# Retrying in 1 seconds
# Failed!
# Retrying in 2 seconds
# Success!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment