Decide whether a short generator-based manager or a reusable class is easier to maintain.
What It Does and Why It Matters
Use @contextmanager and one yield for a straightforward setup/body/cleanup sequence. A class with __enter__ and __exit__ is often better if you need configurable state, multiple methods or an interface reused beyond one block. Both must release resources when the body fails.
Exception suppression requires deliberate logic in either design.
Step-by-Step Example
Start with the complete example below. Read the inputs and predict what the final print statement will show before you run it.
from contextlib import contextmanager
@contextmanager
def active_label(label):
print("start", label)
try:
yield label.upper()
finally:
print("end", label)
with active_label("task") as value:
print(value)
How the Code Works
- The imports make these standard-library tools available: contextlib.
- The definition of active_label creates reusable behavior; its body runs only when called or instantiated as appropriate.
- The structured block controls error handling or resource lifetime, including what happens when an operation fails.
- The print calls display the results. Compare these results with the method’s documented return type and the input used.
Expected output:
start task
TASK
end task
Each displayed line comes from the corresponding calculation or check. The output helps verify the return values before you adapt the example to your own input.
What to Notice
Pay attention to the accepted input types, the returned value and the boundary behavior. Predict what changes if you replace the example input with an empty, zero, negative or missing value, where that value is meaningful for this operation.
If the task uses a library function, inspect its documented exceptions and return type before reusing it inside a larger function.
Where You Would Use This
This matters when working with files, locks, sockets and connections whose lifetime must be controlled. A reliable implementation defines ownership and releases resources on both successful and exceptional paths. Use a small with block before building a more complex manager.
Practice Exercise
Implement the same labeled context as a class and compare the amount of code.
Before running your edited example, write down the result you expect. Then test at least one valid boundary or deliberately invalid value, using appropriate exception handling where necessary.
Reference: official Python documentation for the complete API contract and version notes.
Common Beginner Mistakes
- Yielding twice from a @contextmanager function or forgetting to put cleanup inside finally.
- Releasing the resource only on the successful path rather than when an exception interrupts the block.
Key Takeaways
- Decide whether a short generator-based manager or a reusable class is easier to maintain.
- Use @contextmanager and one yield for a straightforward setup/body/cleanup sequence.
- Implement the same labeled context as a class and compare the amount of code.