In this lesson, you will learn how to create custom context managers using the contextlib library to transform generator functions into clean, reusable setup and teardown logic.
The Problem with Dunder Methods
Previously, you learned how to manage resources like files or database connections using a class with __enter__ and __exit__ methods. While powerful, this approach requires significant boilerplate code—defining a class, setting up state, and handling the exit logic manually. If you just need a simple "open-do-close" pattern, there is a much more elegant way.
The Generator Approach
Because you already understand how yield works for state persistence, you are halfway to mastering this pattern! By using the @contextmanager decorator from the contextlib module, you can turn a generator function into a context manager.
The logic before the yield statement acts as your __enter__ phase, and the code after the yield serves as your __exit__ phase.
from contextlib import contextmanager
@contextmanager
def simple_logger(name):
print(f"--- Starting session: {name} ---")
yield # This is where your 'with' block code runs
print(f"--- Ending session: {name} ---")
# Using the context manager
with simple_logger("Data-Process-01"):
print("Processing sensitive data...")
Why This Matters
When the code hits the with statement, the generator runs until it reaches yield. The execution then pauses, handing control back to your block of code. Once your code inside the with block finishes (or raises an error), the generator resumes, executing whatever code remains after the yield statement.
This approach is highly memory-efficient because it leverages the lazy nature of generators you've been using to process data. It replaces verbose classes with a single, readable function that handles the entire lifecycle of a resource. By wrapping your logic this way, you ensure that your teardown code (like closing a file or clearing a cache) always executes, even if an error occurs during processing.
Key Takeaway: Use the @contextmanager decorator to turn a generator function into a context manager, using yield to separate your setup code from your mandatory cleanup code.