Sub topic 14
Context managers: __enter__ and __exit__
This chapter assumes you can define classes and methods, know what an exception is, and have used with open(...) as f:. It covers how the with statement calls special methods on your own classes.
What `with` does
A context manager is an object that defines __enter__ and __exit__. The with statement calls them in a fixed order:
- Python evaluates the expression after
withand gets the manager object. - It calls
manager.__enter__(). The return value is bound to the name afteras. - The body of the block runs.
- Python calls
manager.__exit__(exc_type, exc, tb). This happens when the block finishes normally, when it raises, and when it leaves throughreturn,breakorcontinue.
A timer example
import time
class Timer:
def __enter__(self):
self.start = time.perf_counter()
return self
def __exit__(self, exc_type, exc, tb):
self.elapsed = time.perf_counter() - self.start
return False # do not suppress exceptions
with Timer() as t:
sum(range(1_000_000))
print(t.elapsed >= 0) # True__enter__ returns self, so t refers to the timer. __exit__ stores the elapsed time. The value is still available after the block because t remains in scope.
The three `__exit__` arguments
If the block ended normally, all three arguments are None. If it raised, they hold the exception class, the exception instance and the traceback.
The return value of __exit__ controls what happens next:
| Return value | Effect |
|---|---|
| `False`, `None` or nothing | The exception, if any, propagates after `__exit__` finishes. |
| A true value | The exception is suppressed and execution continues after the `with` block. |
Returning None by accident is the safe default, because it never hides an error.
Common errors
- Suppressing too much.
return Truehides every exception, including bugs. If you must suppress, checkexc_typefirst and only returnTruefor the specific class you expect. - Raising inside
__exit__. A new exception replaces the original one, so the real cause is harder to find. Keep cleanup code simple. - Forgetting that
__enter__runs first. If__enter__itself raises,__exit__is not called. Acquire resources in__enter__carefully, and release anything partly acquired before re-raising. - Reusing a single-use manager. A manager that holds a file or connection may not work in a second
with. Document whether yours can be reused.
Selective suppression
This manager ignores one specific error and lets every other one through:
class Ignore:
def __init__(self, exc_class):
self.exc_class = exc_class
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
return exc_type is not None and issubclass(exc_type, self.exc_class)
with Ignore(KeyError):
{}['missing']
print('continued') # continued
try:
with Ignore(KeyError):
1 / 0
except ZeroDivisionError:
print('ZeroDivisionError propagated')The expression in __exit__ is False when there is no exception, so a normal block is unaffected.
Exercise
A with block raises ValueError, and the manager's _exit_ has no return statement. Does the code after the with block run, and why?
Show answer
No. A function without a return statement returns None, which is false, so the ValueError is not suppressed. It propagates out of the with statement after _exit_ finishes its cleanup.
Exercise
Write the _exit_ line that suppresses only ZeroDivisionError and lets all other exceptions through.
Show answer
return exctype is ZeroDivisionError (or: return exctype is not None and issubclass(exc_type, ZeroDivisionError) to include subclasses).