Sub topic 4
What `__exit__` receives and how it can suppress exceptions
This chapter assumes you know try/except/finally, the exception class hierarchy, and the basic shape of a class-based context manager (__enter__ returning a value and __exit__ running on the way out). Here we focus on the three arguments __exit__ receives and on what its return value does.
The three arguments
When a with block ends, Python calls __exit__ with three positional arguments:
| Argument | Meaning when the body raised | Value when the body finished normally |
|---|---|---|
| `exc_type` | The exception's class, such as `ValueError` | `None` |
| `exc_value` | The exception instance | `None` |
| `traceback` | A traceback object for where it was raised | `None` |
All three are None together, or none of them are. Testing exc_type is None is the usual way to ask "did the body succeed?"
This manager prints what it receives:
class Show:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
print("type:", exc_type)
print("value:", repr(exc_value))
print("traceback is None:", traceback is None)
return False
with Show():
print("body ok")
try:
with Show():
int("abc")
except ValueError:
print("caught outside")The first block prints None, None, and True. The second prints the ValueError class, the exception instance, and False, and then the except clause runs after __exit__ returns.
The parameter names are only convention. Python passes the values by position, so you can call them et, ev, tb if you like. You must accept all three, though. A signature such as def __exit__(self): raises TypeError at the end of the block.
What counts as an exception here
__exit__ receives anything raised in the body, including BaseException subclasses that except Exception does not catch: KeyboardInterrupt, SystemExit, and GeneratorExit. This matters for cleanup, because it is why with still releases resources when the user presses Ctrl+C. It also matters for suppression, as the next sections show.
Control-flow exits are not exceptions. If the body ends with return, break, or continue, __exit__ is called with (None, None, None) and the jump then completes.
Using the arguments: react without interfering
Many managers only need to know whether the body succeeded. A transaction commits on success and rolls back on failure:
class Transaction:
def __init__(self, log):
self.log = log
def __enter__(self):
self.log.append("begin")
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is None:
self.log.append("commit")
else:
self.log.append(f"rollback ({exc_type.__name__}: {exc_value})")
return False
log = []
try:
with Transaction(log):
raise RuntimeError("disk full")
except RuntimeError:
pass
print(log)The output is ['begin', 'rollback (RuntimeError: disk full)']. The manager did its cleanup and then returned False, so the RuntimeError continued to the caller. Cleanup and error handling stay separate: the manager releases things, and the code around it decides what the error means.
The return value decides the exception's fate
After __exit__ runs, Python looks at its return value only if an exception is in flight.
| `__exit__` does this | Result |
|---|---|
| Returns a falsy value (`False`, `None`, nothing) | The original exception propagates |
| Returns a truthy value (`True`, a non-empty string, a non-zero number) | The exception is suppressed and execution continues after the `with` block |
| Raises a new exception | The new exception replaces the original, which is kept as `__context__` |
A function with no return statement returns None, so propagation is the default. A manager that never mentions a return value never hides anything.
Suppressing selectively
Suppression is a decision about a specific exception, not a switch. This manager swallows only the exception types you list:
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 exc_type is not None check matters. On a normal exit exc_type is None, and issubclass(None, ...) would raise TypeError. The expression also returns a real bool, which keeps the intent obvious.
If the body raised ValueError instead, issubclass would be false, __exit__ would return False, and the ValueError would propagate.
When you want to match on the instance, use isinstance on exc_value. It is safe on a normal exit because isinstance(None, SomeError) is simply False:
class IgnoreMissingFile:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
return isinstance(exc_value, FileNotFoundError)
with IgnoreMissingFile():
open("does-not-exist.txt")
print("no crash")Keeping the error you suppressed
Silent suppression often loses information. A manager can record the exception and let the caller inspect it afterwards:
class Capture:
def __init__(self, *exc_types):
self.exc_types = exc_types
self.error = None
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is not None and issubclass(exc_type, self.exc_types):
self.error = exc_value
return True
return False
with Capture(ZeroDivisionError) as c:
1 / 0
print(c.error)This prints division by zero. Because __enter__ returned self, the as c name stays bound after the block, and c.error is None if nothing went wrong.
What suppression skips
Suppression does not resume the body. The statement that raised is abandoned, along with every statement after it inside the block. Execution continues at the first line after the with.
with Ignore(ZeroDivisionError):
print("before")
1 / 0
print("never printed")
print("after")This prints before and after. Nothing is retried.
Pitfall: accidental truthy returns
The common mistake is not deliberate suppression but suppression you did not intend. Delegating the return value to a helper is a typical cause:
class Buggy:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
return self.release()
def release(self):
print("released")
return True # meant as "release succeeded"
with Buggy():
raise ValueError("lost")
print("this line runs, and the ValueError is gone")release() returns True to report success, and __exit__ passes it along. Python reads it as "handled" and the ValueError vanishes without a trace. The fix is to call the helper as a statement and return a constant:
def __exit__(self, exc_type, exc_value, traceback):
self.release()
return FalseA good habit is that every __exit__ ends with an explicit return False, unless suppression is the whole point of the class. A reader can then see at a glance that the exception is not swallowed.
Raising from inside `__exit__`
If __exit__ raises, the new exception propagates instead of the original. Python records the original as __context__, so the traceback shows both. That is useful for translating low-level errors into domain errors:
class ConfigErrors:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is KeyError:
raise LookupError("config key missing") from exc_value
return False
try:
with ConfigErrors():
{}["port"]
except LookupError as e:
print(e, "| cause:", repr(e.__cause__))The from exc_value clause sets __cause__ explicitly, which makes the traceback read "the above exception was the direct cause of the following exception".
Do not re-raise the exception you were given with raise exc_value. It adds nothing and clutters the traceback. To let the original through, return a falsy value, which is the contract __exit__ is designed around.
A related rule is that an exception raised during cleanup is itself a problem. If your cleanup code can fail, for example while closing a network connection, decide whether that failure should mask the original error. Python will not make that choice for you.
Summary of decision criteria
Use these questions when writing __exit__:
- Does this manager only clean up? Return
Falseand let the caller handle errors. - Is a specific, expected exception harmless at this call site? Suppress that type only, and consider recording it.
- Should a low-level error become a different error? Raise the new one with
from exc_value. - Is the return value ever computed from something else? Make sure it cannot be truthy by accident.
Exercise
What does this program print, and why? class Quiet: def _enter(self): return self def exit(self, exctype, excvalue, traceback): return exctype is ValueError for value in ["1", "x", None]: try: with Quiet(): print(int(value)) except TypeError: print("type error") print("done")
Show answer
It prints 1, then type error, then done. For "1" the body prints 1, and _exit receives (None, None, None), so exctype is ValueError is False and nothing is suppressed. For "x", int raises ValueError, _exit returns True, the exception is suppressed, and nothing is printed for that iteration. For None, int(None) raises TypeError. exctype is ValueError is False, so the TypeError propagates to the except clause, which prints "type error". Note the identity test only matches ValueError exactly, not its subclasses. Using issubclass would be the more general choice.