Sub topic 14
Context managers: __enter__ and __exit__
This chapter assumes you can define classes with regular methods, use try/finally, and have used with open(...). It builds on the earlier chapters, where syntax maps to methods looked up on an object's type.
What the with statement calls
A context manager is any object whose type defines __enter__ and __exit__. The with statement calls these two methods around a block of code. This guarantees that cleanup runs however the block ends: normally, through return, break, continue, or an exception.
class Trace:
def __enter__(self):
print('enter')
return self
def __exit__(self, exc_type, exc, tb):
print('exit', exc_type.__name__ if exc_type else None)
return False
with Trace() as t:
print('body')This prints enter, body, then exit None. The None means the block finished without an exception.
The same logic written out
The statement behaves roughly like the function below. This is a simplification, but it shows the key facts: both methods are looked up on the type, and __exit__ is only used if __enter__ succeeded.
def run_with(manager, body):
enter = type(manager).__enter__
exit_ = type(manager).__exit__
value = enter(manager)
try:
body(value)
except BaseException as e:
if not exit_(manager, type(e), e, e.__traceback__):
raise
else:
exit_(manager, None, None, None)
class Demo:
def __enter__(self):
return 'resource'
def __exit__(self, exc_type, exc, tb):
print('cleanup')
return False
run_with(Demo(), print) # resource, then cleanupThe three arguments to __exit__
__exit__ receives the exception type, the exception instance, and the traceback. All three are None when the block ends normally. The method must accept all three, even if it ignores them.
The return value matters only when an exception occurred:
- A false value (
False,None, or no return statement) lets the exception continue to propagate. - A true value suppresses the exception, and execution continues after the
withblock.
Because a missing return gives None, the default is to propagate. This is the safe default. The timer from the spine returns False explicitly to document that choice.
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) # TrueThe timer records elapsed even if the body raises, because __exit__ always runs.
What __enter__ returns
The value after as is whatever __enter__ returns. It is not necessarily the manager itself. If you forget the return, the name is bound to None, which is a common source of confusing AttributeError messages.
The next class returns a different object. It snapshots a dictionary and restores it if the block fails.
class Transaction:
def __init__(self, store):
self.store = store
def __enter__(self):
self.snapshot = dict(self.store)
return self.store
def __exit__(self, exc_type, exc, tb):
if exc_type is not None:
self.store.clear()
self.store.update(self.snapshot)
return False
data = {'a': 1}
try:
with Transaction(data) as d:
d['a'] = 2
d['b'] = 3
raise RuntimeError('boom')
except RuntimeError:
pass
print(data) # {'a': 1}The changes are rolled back, and the RuntimeError still reaches the caller because __exit__ returned False.
Suppressing exceptions on purpose
Return True only when you are certain the exception is expected. Check the type first, and return a true value for no other case.
class Ignore:
def __init__(self, *types):
self.types = types
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
return exc_type is not None and issubclass(exc_type, self.types)
with Ignore(KeyError):
{}['missing']
print('continued') # continuedThe expression is False when there is no exception, so normal exits are unaffected. A ValueError inside this block would still propagate.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| `__enter__` has no `return` | The `as` name is `None` | Return `self` or the resource |
| `__exit__(self)` with no extra parameters | `TypeError` when the block ends | Accept `exc_type, exc, tb` |
| Cleanup placed in `__enter__` failure path | `__exit__` is not called if `__enter__` raises | Clean up inside `__enter__` before re-raising |
| Returning a truthy value by accident | Exceptions are silently swallowed | Return `False` or `None` unless suppressing deliberately |
| Reusing one instance for nested or repeated blocks | State such as `start` is overwritten | Create a new instance per `with`, or store state on a stack |
The third row deserves attention. If __enter__ acquires two resources and the second acquisition fails, Python does not call __exit__, so __enter__ must release the first one itself.
Several managers and exceptions in cleanup
A single with can list several managers: with A() as a, B() as b:. They are entered left to right and exited in reverse order, like nested with statements. If B().__enter__ raises, A().__exit__ still runs.
If __exit__ itself raises, the new exception replaces the original one. Python attaches the original as __context__, so the traceback shows both. Keep cleanup code simple and guard steps that can fail.
Relationship to contextlib
For simple cases, contextlib.contextmanager turns a generator into a context manager without writing a class. Writing the class is preferable when the manager keeps state you want to inspect afterwards, such as t.elapsed, or when it is reused across a codebase with a clear name and documentation.
Exercises
Exercise
A class defines __exit__ that ends with return True after logging the error. What happens when the body of the with block raises ValueError, and what is the safer alternative?
Show answer
The ValueError is suppressed, so execution continues after the with block as if nothing happened. The safer alternative is to log and then return False (or None) so the exception propagates, or to return True only after checking that exc_type is an expected type.
Exercise
Write a context manager class Cd that changes the working directory with os.chdir on entry and restores the previous directory on exit, even when the body raises. Which value should __enter__ return?
Show answer
import os
class Cd:
def _init(self, path):
self.path = path
def enter(self):
self.previous = os.getcwd()
os.chdir(self.path)
return self.path
def exit(self, exctype, exc, tb):
os.chdir(self.previous)
return False
Returning the path (or self) is reasonable. Returning False from __exit__ leaves any exception from the body to propagate after the directory is restored.