Python

Context Manager via @contextmanager

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Build a custom context manager without writing a class — just a generator with one `yield`. The code before yield runs on enter, after yield runs on exit (even on exception).
Python
Raw
import os
from contextlib import contextmanager

@contextmanager
def cwd(path: str):
    """Temporarily chdir into `path`, restoring on exit."""
    original = os.getcwd()
    try:
        os.chdir(path)
        yield path
    finally:
        os.chdir(original)

with cwd("/tmp"):
    print(os.getcwd())     # /tmp
print(os.getcwd())         # back to wherever you were

@contextmanager
def stopwatch(label: str):
    import time
    start = time.perf_counter()
    yield
    print(f"{label}: {(time.perf_counter() - start) * 1000:.2f} ms")

with stopwatch("expensive op"):
    sum(i * i for i in range(1_000_000))
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.