Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # ------------------ errors supressor ----------------
- class CatchErrors:
- def __init__(self, errors=Exception):
- self.errors = errors
- def __enter__(self):
- ...
- def __exit__(self, exc_type, exc_val, exc_tb):
- if exc_type is None:
- return
- return issubclass(exc_type, self.errors)
- manager = CatchErrors()
- with manager:
- 5 / 0 # ZeroDivisionError
- manager = CatchErrors(errors=(AttributeError, RuntimeError, ZeroDivisionError))
- with manager:
- 5 / 0 # ZeroDivisionError
- manager = CatchErrors(KeyError)
- with manager:
- 5 / 0 # ZeroDivisionError
- # ------- timer --------------
- import time
- import random
- class Timer:
- start = None
- end = None
- @property
- def total(self):
- return self.end - self.start
- def __enter__(self):
- self.start = time.perf_counter()
- return self
- def __exit__(self, exc_type, exc_val, exc_tb):
- self.end = time.perf_counter()
- data = [random.random() for _ in range(1_000_000)]
- with Timer() as manager:
- sorted(data)
- print(f"Total: {manager.total} sec")
- # ---------------- access provider -----------
- import os
- class AccessProvider:
- old = None
- def __enter__(self):
- self.old = os.environ.copy()
- os.environ["USER"] = "test_user"
- os.environ["PASSWORD"] = "P@55w0rd"
- def __exit__(self, exc_type, exc_val, exc_tb):
- os.environ.clear()
- os.environ.update(self.old)
- with AccessProvider():
- user = os.environ["USER"]
- password = os.environ["PASSWORD"]
- print(f"Connect to DB using {user=}, {password=}")
- user = os.environ["USER"]
- password = os.environ["PASSWORD"]
- print(f"Connect to DB using {user=}, {password=}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement