Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from random import randint
- class retry(object):
- def __init__(self, attempts, **kwargs):
- self.outputs = []
- self.attempt = 0
- self.attempts = attempts
- if kwargs:
- for key, value in kwargs.items():
- setattr(self, key, value)
- print("{} = {}".format(key, value), end=", ")
- print()
- def __call__(self, f):
- def wrapper(*args, **kwargs):
- try:
- _kwargs_names = [attr for attr in kwargs.keys() if attr in self.__dict__.keys()]
- print("Kwargs:", _kwargs_names)
- result = None
- while self.attempt < self.attempts:
- for attr in _kwargs_names:
- kwargs[attr] = getattr(self, attr)
- result = f(*args, **kwargs)
- self.outputs.append(result)
- #print("Outputs: ", self.outputs)
- if result%5 > 3:
- return result
- self.attempt += 1
- return result
- finally:
- print("Outputs: ", len(self.outputs), self.outputs)
- self.attempt = 0
- self.outputs.clear()
- return wrapper
- @retry(attempts=5, name="Add", _id=853)
- def add(a, b, **kwargs):
- retry = kwargs.get("attempt", 0)
- print("retry:", retry)
- return a+b+retry
- add(1, 1, attempt=None)
- add(2, 10, attempt=None)
- @retry(attempts=10, name="Random")
- def random(u_limit, l_limit, **kwargs):
- return randint(u_limit, l_limit)
- random(1, 10, attempt=None)
- random(2, 20, name=None)
- random(3, 30)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement