@contextmanager
contextlib.contextmanager turns a generator function into a context manager, simplifying resource management without writing a class.
contextlib.contextmanager turns a generator function into a context manager, simplifying resource management without writing a class.
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
The yield must be inside a try/finally to guarantee cleanup.