SyntaxStudy
Sign Up
Python @contextmanager Decorator
Python Intermediate 4 min read

@contextmanager Decorator

@contextmanager

contextlib.contextmanager turns a generator function into a context manager, simplifying resource management without writing a class.

Example
from contextlib import contextmanager

@contextmanager
def managed_resource():
    print("Setup")
    try:
        yield "resource"
    finally:
        print("Teardown")

with managed_resource() as r:
    print(f"Using {r}")
# Setup -> Using resource -> Teardown
Pro Tip

The yield must be inside a try/finally to guarantee cleanup.