0Pricing
Python Academy · Lesson

contextlib: @contextmanager

Create context managers concisely with the contextlib decorator.

Why contextlib?

contextlib.contextmanager lets you write a context manager as a generator function instead of a class, reducing boilerplate.

from contextlib import contextmanager

@contextmanager
def managed():
    print("setup")
    yield
    print("teardown")

with managed():
    print("inside")

Yielding a Value

Whatever you yield is bound to the as variable in the with statement.

from contextlib import contextmanager

@contextmanager
def temp_list():
    lst = []
    yield lst
    print(f"Final list: {lst}")

with temp_list() as lst:
    lst.append(1)
    lst.append(2)

All lessons in this course

  1. The with Statement in Depth
  2. __enter__ and __exit__ Protocol
  3. contextlib: @contextmanager
  4. Practical Context Manager Patterns
← Back to Python Academy