Context manager is an object that manages resources (files, connections) using with.
Basic usage:
1# File2with open("file.txt", "r") as f:3 data = f.read()4# File is automatically closed
Creating your own context manager:
1from contextlib import contextmanager23@contextmanager4def timer(name):5 import time6 start = time.time()7 yield # Code inside with executes here8 end = time.time()9 print(f"{name} took {end - start:.2f}s")1011# Usage12with timer("sleep"):13 time.sleep(1)14# "sleep took 1.00s"
Class-based:
1class Timer:2 def __enter__(self):3 import time4 self.start = time.time()5 return self67 def __exit__(self, exc_type, exc_val, exc_tb):8 import time9 self.end = time.time()10 print(f"Took {self.end - self.start:.2f}s")11 return False # Don't suppress exceptions