Skip to content

Instantly share code, notes, and snippets.

@nackjicholson
Last active October 1, 2018 17:51
Show Gist options
  • Save nackjicholson/f36e8298a8872dd5c881fa3912edaeb0 to your computer and use it in GitHub Desktop.
Save nackjicholson/f36e8298a8872dd5c881fa3912edaeb0 to your computer and use it in GitHub Desktop.
Retriable class decorator, which would allow declaration time AND runtime resetting of decorator properties.
import time
from functools import wraps, update_wrapper
def scaled_retries(attempts, sleeptime, sleepscale):
scaled_sleeptime = sleeptime
for attempt_no in range(attempts):
yield attempt_no + 1, scaled_sleeptime
scaled_sleeptime *= sleepscale
# don't need to sleep if this was the last attempt
if attempt_no < attempts - 1:
time.sleep(scaled_sleeptime)
class Retriable:
def __init__(
self,
func,
attempts=5,
sleeptime=1,
sleepscale=1.5,
cleanup=None,
fail_fast_exceptions=None
):
self.func = func
self.attempts = attempts
self.sleeptime = sleeptime
self.sleepscale = sleepscale
self.cleanup = cleanup
self.fail_fast_exceptions = fail_fast_exceptions
update_wrapper(self, func)
def __call__(self, *args, **kwargs):
retries = scaled_retries(self.attempts, self.sleeptime, self.sleepscale)
for attempt_no, scaled_sleeptime in retries:
# noinspection PyBroadException
try:
return self.func(*args, **kwargs)
except Exception as e:
if self.fail_fast_exceptions and isinstance(e, self.fail_fast_exceptions):
raise
if self.cleanup:
self.cleanup(attempt_no, scaled_sleeptime, e)
if attempt_no == self.attempts:
raise
if __name__ == '__main__':
count = 0
@Retriable
def sketchy_sum(a, b):
global count
if count < 4:
count += 1
raise FileNotFoundError()
return a + b
def log(_name, _args, _kwargs, attempt_no, next_sleep, e):
print(f'sketchy sum attempt {attempt_no} failed with {e} and will retry after {next_sleep}')
sketchy_sum.cleanup = log
# safe_sum = retriable(cleanup=log, fail_fast_exceptions=(FileNotFoundError,))(sketchy_sum)
# safe_sum = retriable(cleanup=log)(sketchy_sum)
print(sketchy_sum(2, 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment