Skip to content

Instantly share code, notes, and snippets.

@estasney
Last active January 25, 2021 15:55
Show Gist options
  • Save estasney/642eb3bf597701dce02c2e5434cd0f89 to your computer and use it in GitHub Desktop.
Save estasney/642eb3bf597701dce02c2e5434cd0f89 to your computer and use it in GitHub Desktop.
Backoff Decorator - Accepting Parameters
import time
import random
class BackOffDecorator(object):
def __init__(self, max_tries, delay, backoff_rate):
self.max_tries = max_tries
self.tries = 0
self.delay = delay
self.backoff_rate = backoff_rate
self.func_to_decorate = None
def wrapper_function(self, *args, **kwargs):
if self.tries < self.max_tries:
try:
return self.func_to_decorate(*args, **kwargs)
except Exception as e:
self.tries += 1
if self.tries >= self.max_tries:
print("Reached Maximum Tries {}".format(self.max_tries))
raise
else:
tries_remaining = self.max_tries - self.tries
sleep_time = self.delay * self.tries * self.backoff_rate
print("{} Occurred. {} Tries remaining".format(type(e), tries_remaining))
print("Sleeping For {} seconds".format(sleep_time))
time.sleep(sleep_time)
self.wrapper_function(*args, **kwargs)
def __call__(self, *args, **kwargs):
self.func_to_decorate = args[0]
return self.wrapper_function
@BackOffDecorator(max_tries=3, delay=1, backoff_rate=3)
def demo_function(r):
x = random.randint(0, r)
print("r is {}".format(r))
print("x is {}".format(x))
if x == 1:
raise IndexError
return x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment