Advertisement
Guest User

Class decorator

a guest
Jul 22nd, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. from random import randint
  2.  
  3. class retry(object):
  4.    
  5.     def __init__(self, attempts, **kwargs):
  6.         self.outputs = []
  7.         self.attempt = 0
  8.         self.attempts = attempts
  9.         if kwargs:
  10.             for key, value in kwargs.items():
  11.                 setattr(self, key, value)
  12.                 print("{} = {}".format(key, value), end=", ")
  13.             print()
  14.    
  15.     def __call__(self, f):
  16.         def wrapper(*args, **kwargs):
  17.             try:
  18.                 _kwargs_names = [attr for attr in kwargs.keys() if attr in self.__dict__.keys()]
  19.                 print("Kwargs:", _kwargs_names)
  20.                 result = None
  21.                 while self.attempt < self.attempts:
  22.                     for attr in _kwargs_names:
  23.                         kwargs[attr] = getattr(self, attr)
  24.                     result = f(*args, **kwargs)
  25.                     self.outputs.append(result)
  26.                     #print("Outputs: ", self.outputs)
  27.                     if result%5 > 3:
  28.                         return result
  29.                     self.attempt += 1
  30.                 return result
  31.             finally:
  32.                 print("Outputs: ", len(self.outputs), self.outputs)
  33.                 self.attempt = 0
  34.                 self.outputs.clear()
  35.         return wrapper
  36.        
  37.  
  38. @retry(attempts=5, name="Add", _id=853)
  39. def add(a, b, **kwargs):
  40.     retry = kwargs.get("attempt", 0)
  41.     print("retry:", retry)
  42.     return a+b+retry
  43.  
  44. add(1, 1, attempt=None)
  45. add(2, 10, attempt=None)
  46.  
  47. @retry(attempts=10, name="Random")
  48. def random(u_limit, l_limit, **kwargs):
  49.     return randint(u_limit, l_limit)
  50.  
  51. random(1, 10, attempt=None)
  52. random(2, 20, name=None)
  53. random(3, 30)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement