Trace how a context manager responds when its body raises an exception.
What It Does and Why It Matters
For a class-based context manager, __enter__() supplies the resource and __exit__(type, value, traceback) runs when leaving. If __exit__ returns True, the exception is suppressed; returning False or None lets it propagate. Suppression should be intentional and narrowly scoped because it may hide programming errors.
An exception raised inside __enter__ does not trigger that same manager’s __exit__ automatically.
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.
class Notice:
def __enter__(self):
print("enter")
return self
def __exit__(self, error_type, error, trace):
print("exit", error_type.__name__ if error_type else "normal")
return False
try:
with Notice():
raise ValueError("example")
except ValueError:
print("handled outside")
How the Code Works
- The definition of Notice 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.
- The raised ValueError is passed to __exit__; because __exit__ returns False, the exception propagates to the outside except block.
Expected output:
enter
exit ValueError
handled outside
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
Change the body to succeed, then raise a different exception, and compare the order of messages.
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
- Returning True from __exit__ without realizing that doing so hides exceptions.
- Releasing the resource only on the successful path rather than when an exception interrupts the block.
Key Takeaways
- Trace how a context manager responds when its body raises an exception.
- For a class-based context manager, __enter__() supplies the resource and __exit__(type, value, traceback) runs when leaving.
- Change the body to succeed, then raise a different exception, and compare the order of messages.