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
- The with Statement in Depth
- __enter__ and __exit__ Protocol
- contextlib: @contextmanager
- Practical Context Manager Patterns