Sub topic 2
What `__exit__` Receives and How It Can Suppress Exceptions
Assume you know Python classes, try/except/finally, generators, and decorators. A context manager controls setup and cleanup around a with block.
The `__exit__` method
When the block finishes, Python calls:
__exit__(exc_type, exc_value, traceback)The arguments describe an exception raised inside the block:
| Situation | `exc_type` | `exc_value` | `traceback` |
|---|---|---|---|
| No exception | `None` | `None` | `None` |
| Exception raised | Exception class | Exception object | Traceback object |
Returning a false value, such as False or None, lets the exception continue. Returning True tells Python that the context manager handled it.
class Ignore:
def __init__(self, *exception_types):
self.exception_types = exception_types
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is None:
return False
return issubclass(exc_type, self.exception_types)
with Ignore(KeyError):
{}["missing"]
print("execution continues")This suppresses KeyError, but not unrelated exceptions.
Class-based context managers
__enter__ prepares the resource and returns the value used by as. __exit__ performs cleanup whether the block succeeds or fails.
class Connection:
def __enter__(self):
print("opened")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("closed")
return False
with Connection() as connection:
print("using connection")Generator-based context managers
The @contextmanager decorator turns a generator into a context manager. Code before yield is setup. The yielded value becomes the as value. A finally block guarantees cleanup.
from contextlib import contextmanager
@contextmanager
def resource():
print("opened")
try:
yield "resource value"
finally:
print("closed")
with resource() as value:
print(value)If the block raises an exception, Python resumes the generator at yield by raising that exception there. The finally block still runs. Unless the generator catches the exception and returns normally, the exception propagates.
Exercise
What should __exit__ return when a context manager must clean up but must not hide exceptions?
Show answer
Return False or None. Cleanup still runs, and the original exception propagates.