Advertisement
fkudinov

Context Managers CookBook

Nov 28th, 2024 (edited)
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.79 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. user = os.environ["USER"]
  92. password = os.environ["PASSWORD"]
  93. print(f"Connect to DB using {user=}, {password=}")
  94.  
  95.  
  96.  
  97.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement