Advertisement
Korotkodul

C. Попробуй еще раз

Sep 21st, 2024 (edited)
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.19 KB | None | 0 0
  1. from typing import Callable, TypeVar
  2. from functools import wraps
  3. import time
  4.  
  5. T = TypeVar("T")
  6.  
  7.  
  8. def retry(retries: int = 3, timeout: float = 1) -> Callable[[T], T]:
  9.     # ваш код
  10.     def take_in_func(func):
  11.         @wraps(func)
  12.         def wrapper(*args, **kwargs):
  13.             mistake = -1
  14.             for i in range(retries):
  15.                 try:
  16.                     res = func(*args, **kwargs)
  17.                     return res
  18.                 except Exception as exp:
  19.                     mistake = exp
  20.                     time.sleep(timeout)
  21.             return mistake
  22.         return wrapper
  23.     return take_in_func
  24.  
  25.  
  26. def raiser_factory(stop_on: int = 2) -> Callable:
  27.     call_counter = 0
  28.  
  29.     def raiser(*args, **kwargs) -> None:
  30.         nonlocal call_counter
  31.  
  32.         if call_counter != 0 and call_counter % stop_on == 0:
  33.             return
  34.  
  35.         call_counter += 1
  36.         raise Exception
  37.  
  38.     return raiser
  39.  
  40. # первый пример
  41. raiser = retry()(raiser_factory())
  42. raiser()
  43.  
  44. # второй пример
  45. raiser = retry()(raiser_factory(stop_on=4))
  46.  
  47. try:
  48.     raiser()
  49.     was_raised = False
  50.  
  51. except Exception:
  52.     was_raised = True
  53.  
  54. assert was_raised
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement