SyntaxStudy
Sign Up
Python Custom Context Managers
Python Intermediate 4 min read

Custom Context Managers

Context Managers

Implement __enter__ and __exit__ for custom resource management, or use contextlib.contextmanager with a generator.

Example
from contextlib import contextmanager

@contextmanager
def timer(label: str = ""):
    import time
    start = time.perf_counter()
    try:
        yield
    finally:
        elapsed = time.perf_counter() - start
        print(f"{label}: {elapsed:.3f}s")

with timer("db query"):
    results = db.fetch_all()

@contextmanager
def temp_directory():
    import tempfile, shutil
    path = tempfile.mkdtemp()
    try: yield path
    finally: shutil.rmtree(path)
Pro Tip

The yield expression in a contextmanager generator replaces __enter__; the finally block is __exit__.