fkudinov

Context Managers CookBook

Nov 28th, 2024 (edited)
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.50 KB | Source Code | 0 0
  1. # ------------------ errors supressor ----------------
  2.  
  3. class CatchErrors:
  4.  
  5.     def __init__(self, errors=Exception):
  6.         self.errors = errors
  7.  
  8.     def __enter__(self):
  9.         ...
  10.  
  11.     def __exit__(self, exc_type, exc_val, exc_tb):
  12.         if exc_type is None:
  13.             return
  14.  
  15.         return issubclass(exc_type, self.errors)
  16.  
  17.  
  18. manager = CatchErrors()
  19. with manager:
  20.     5 / 0  # ZeroDivisionError
  21.  
  22.  
  23. manager = CatchErrors(errors=(AttributeError, RuntimeError, ZeroDivisionError))
  24. with manager:
  25.     5 / 0  # ZeroDivisionError
  26.  
  27. manager = CatchErrors(KeyError)
  28. with manager:
  29.     5 / 0  # ZeroDivisionError
  30.  
  31.  
  32.  
  33.  
  34. # -------  timer --------------
  35.  
  36.  
  37. import time
  38. import random
  39.  
  40.  
  41. class Timer:
  42.  
  43.     start = None
  44.     end = None
  45.  
  46.     @property
  47.     def total(self):
  48.         return self.end - self.start
  49.  
  50.     def __enter__(self):
  51.         self.start = time.perf_counter()
  52.         return self
  53.  
  54.     def __exit__(self, exc_type, exc_val, exc_tb):
  55.         self.end = time.perf_counter()
  56.  
  57.  
  58. data = [random.random() for _ in range(1_000_000)]
  59. with Timer() as manager:
  60.     sorted(data)
  61.  
  62.  
  63. print(f"Total: {manager.total} sec")
  64.  
  65.  
  66. # ---------------- access provider -----------
  67.  
  68. import os
  69.  
  70.  
  71. class AccessProvider:
  72.  
  73.     old = None
  74.  
  75.     def __enter__(self):
  76.         self.old = os.environ.copy()
  77.         os.environ["USER"] = "test_user"
  78.         os.environ["PASSWORD"] = "P@55w0rd"
  79.  
  80.     def __exit__(self, exc_type, exc_val, exc_tb):
  81.         os.environ.clear()
  82.         os.environ.update(self.old)
  83.  
  84.  
  85. with AccessProvider():
  86.     user = os.environ["USER"]
  87.     password = os.environ["PASSWORD"]
  88.     print(f"Connect to DB using {user=}, {password=}")
  89.  
  90.  
  91. os.environ["USER"]
  92. password = os.environ["PASSWORD"]
  93. print(f"Connect to DB using {user=}, {password=}")
  94.  
  95.  
  96. # -----------    redirect stdout ---------
  97.  
  98. # приблизна реалізація
  99. import sys
  100.  
  101.  
  102. class RedirectStdout:
  103.  
  104.     def __init__(self, target):
  105.         self.target = target          # Зберегти таргет
  106.  
  107.     def __enter__(self):
  108.         sys.stdout = self.target      # Підмінити таргет
  109.         return sys.stdout
  110.  
  111.     def __exit__(self, exc_type, exc_val, exc_tb):
  112.         sys.stdout = sys.__stdout__   # Повернути оригінальне значення
  113.  
  114.  
  115.  
  116. from contextlib import redirect_stdout
  117. from io import StringIO
  118.  
  119.  
  120. with StringIO() as file:
  121.     with redirect_stdout(file):
  122.         print("Hi there")
  123.         print("How are you")
  124.  
  125.     data = file.getvalue()
  126.  
  127.  
  128. print(f"Captured stdout: {data}")
  129.  
  130.  
  131.  
  132. # -----------  catch_errors  generator context manager  --------------
  133.  
  134. from contextlib import contextmanager
  135.  
  136.  
  137. @contextmanager
  138. def catch_errors(errors=Exception):
  139.  
  140.     print("__enter__ logic")
  141.     try:
  142.         yield "resource"
  143.     except errors:
  144.         pass
  145.     finally:
  146.         print("__exit__ logic")
  147.  
  148.  
  149. manager = catch_errors()
  150. with manager:
  151.     5 / 0
  152.  
  153.  
  154. manager = catch_errors(errors=(AttributeError, RuntimeError, ZeroDivisionError))
  155. with manager:
  156.     5 / 0
  157.  
  158.  
  159. manager = catch_errors(KeyError)
  160. with manager:
  161.     5 / 0
  162.  
  163.  
  164. # -------------  throttle http homework   ----------------
  165.  
  166. # pip install requests
  167.  
  168. import requests
  169.  
  170.  
  171. class ThrottleHttp:
  172.     ...
  173.  
  174.  
  175. with ThrottleHttp() as throttle:
  176.     try:
  177.         requests.get("https://swapi.dev/api/people/1/")
  178.     except ConnectionError:
  179.         ...
  180.  
  181. assert len(throttle.throttled_requests) == 1
  182.  
  183.  
  184. res = requests.get("https://swapi.dev/api/people/1/")
  185. assert res.status_code == 200
  186.  
  187.  
  188.  
Advertisement
Add Comment
Please, Sign In to add comment