Deterministic cleanup
Release a lock, file, socket, or other resource when a with block ends.
Python · Module
__exit__ is the context-manager hook Python invokes when leaving a with block. It receives exception details when the block fails and can suppress the exception by returning a true value.
When a with block finishes, Python calls the context manager’s __exit__ method. It receives the exception type, value, and traceback when an exception caused the block to end, or three None values on normal completion; a true return suppresses that exception.
def __exit__(self, exc_type, exc_value, traceback):| Name | Type | Description |
|---|---|---|
exc_type | type[BaseException] | None | Exception class, or None when no exception caused the exit. |
exc_value | BaseException | None | Exception instance, or None on normal completion. |
traceback | traceback | None | Traceback object, or None on normal completion. |
A truthy value suppresses an exception from the with suite; a false value allows it to be reraised. On non-exception exits, the return value is ignored.
class Managed:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
return exc_type is ValueError
with Managed():
raise ValueError("handled")The context manager suppresses a ValueError raised inside the with block.
Release a lock, file, socket, or other resource when a with block ends.
Convert a specific, expected exception into normal control flow.
Record exception details while still allowing unexpected failures to propagate.
Python calls __exit__ when the with suite ends. On an exception, it receives the exception type, value, and traceback; otherwise all three arguments are None.
Follow-up: What does a false return do after an exception? The exception is reraised, preserving normal error propagation.
A truthy return from __exit__ suppresses an exception raised in the with suite. A false return causes that exception to be reraised.
Follow-up: Is the return value used on normal completion? No; it is ignored when no exception caused the suite to exit.
A context manager’s __exit__ method is invoked as part of leaving a with statement. Its return value controls only exception suppression, not ordinary completion.
Follow-up: What should __exit__ return when cleanup should not handle errors? Return a false value, commonly None, so exceptions propagate.
__enter__with statementcontext managercontextlib.AbstractContextManagercontextlib.ExitStack