Sub topic 4
What __exit__ receives and how it can suppress exceptions
This chapter assumes you know try/except/finally, how with calls __enter__ and __exit__, and how Python classes and exceptions work. Here you will look closely at the three arguments __exit__ receives and at what its return value does.
The three arguments
When the body of a with block ends, Python calls __exit__ with three arguments. They describe how the block ended.
| Situation | exc_type | exc_value | traceback |
|---|---|---|---|
| Block finished normally | `None` | `None` | `None` |
| Block raised an exception | the exception class | the exception instance | a traceback object |
So the first argument is the quickest way to check whether an error happened:
class Report:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is None:
print("block finished normally")
else:
print(f"block failed with {exc_type.__name__}: {exc_value}")
return False
with Report():
1 / 0This prints the failure message, and then the ZeroDivisionError continues upward as usual.
The return value decides what happens next
Python looks at the truth value of what __exit__ returns, but only when an exception occurred.
- A false value (
False,None, or noreturnat all) means the exception was not handled. Python re-raises it after__exit__returns. - A true value means the exception was handled. Python discards it, and execution continues with the statement after the
withblock.
Because a missing return gives None, the default is to let exceptions propagate. That is the safe default. Most managers only need to release a resource and should not decide that an error is acceptable.
Suppressing selected exceptions
Suppression should be narrow. Check the type, and swallow only what you mean to swallow.
class Ignore:
def __init__(self, *exc_types):
self.exc_types = exc_types
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
# A true return value tells Python the exception was handled.
return exc_type is not None and issubclass(exc_type, self.exc_types)
with Ignore(KeyError):
{}["missing"]
print("execution continues")The expression exc_type is not None and issubclass(...) matters. When the block succeeds, exc_type is None, and issubclass(None, ...) would raise a TypeError. The is not None check short-circuits first. Any exception that is not a KeyError produces False, so it still propagates.
Do not re-raise the exception yourself
If you want the exception to propagate, return a false value. Do not write raise exc_value inside __exit__. Re-raising there adds confusing extra frames to the traceback and can replace the original context. Raising a different exception from __exit__ is legitimate, for example to translate a low-level error into your own type. Use raise NewError(...) from exc_value so the cause stays visible.
Cleanup errors
If __exit__ itself raises, that new exception takes the place of the original one, which becomes its __context__. Keep cleanup code simple, and guard calls that might fail if the original error is more important.
Summary of rules
- Treat
exc_type is Noneas the success case. - Return a false value (or nothing) to let exceptions propagate.
- Return
Trueonly after deciding the specific exception is handled. - Never raise the received exception again by hand. Return
Falseinstead.
Exercise
A context manager's __exit__ ends with return True and no other logic. The block inside with contains open("missing.txt"), which raises FileNotFoundError, followed by print("done"). What happens, and why is this a bad design?
Show answer
The FileNotFoundError is raised inside the block, Python calls __exit__, and the true return value tells Python the exception was handled. The error is discarded, so print("done") is skipped (the block stops at the failing line), and execution resumes after the with statement with no sign that anything failed. It is a bad design because it hides every exception, including unrelated bugs and KeyboardInterrupt. A better __exit__ checks exc_type and returns True only for the specific exception types it intends to suppress.
Exercise
Write an __exit__ method that suppresses ValueError but lets every other exception propagate, and that works correctly when the block raises nothing.
Show answer
def _exit(self, exctype, excvalue, traceback):
return exctype is not None and issubclass(exctype, ValueError)
When the block succeeds, `exctype is None, so the expression is False and issubclass is never called. For a ValueError (or a subclass) it returns True, which suppresses it. For any other exception type it returns False`, so the exception propagates.