Sub topic 5
Writing a context manager as a class
This chapter assumes you know Python classes and methods, try/except/finally, and the basic with open(...) pattern. You should also know that with calls __enter__ and __exit__. Here you will use those two methods to build managers of your own. Generator-based managers come in the next chapters.
The shape of a class-based manager
A class becomes a context manager when it defines two methods:
__enter__(self)runs when thewithblock starts. Its return value is bound to the name afteras.__exit__(self, exc_type, exc_value, traceback)runs when the block ends, whether it finished normally, raised, or returned early.
Python looks these methods up on the class, not on the instance. Assigning obj.__enter__ = ... on one object has no effect on with obj:.
class Minimal:
def __enter__(self):
print("enter")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("exit", exc_type)
return False
with Minimal() as m:
print("body", type(m).__name__)This prints enter, then body Minimal, then exit None. The None means the block raised nothing.
Designing `__enter__`
__enter__ does the setup, and it decides what the as name refers to. There are three common choices.
- Return
self. Use this when the manager itself is the useful object, as in a timer that exposeselapsed. - Return the acquired resource.
open()does this:with open(p) as fbinds the file, not a wrapper. - Return nothing. If the block needs no handle, as with a lock, leave the return value out. Writing
as xthen givesNone, which is almost always a bug.
The timer from earlier chapters shows the first choice:
import time
class Timer:
def __enter__(self):
self.start = time.perf_counter()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.elapsed = time.perf_counter() - self.start
return False # do not suppress exceptions
with Timer() as t:
sum(range(1_000_000))
print(f"{t.elapsed:.4f} seconds")elapsed is set in __exit__, so it also exists if the body raised. The timing is recorded and the exception still propagates. You can read t.elapsed after the block, because the as name stays in scope.
Designing `__exit__`
__exit__ always takes three arguments after self. If the block ended without an exception, all three are None. Otherwise they are the exception class, the exception instance, and the traceback.
The return value controls what happens to an exception:
| `__exit__` returns | Effect |
|---|---|
| `False`, `None`, or any false value | Any exception from the body propagates. |
| `True` or any true value | The exception is suppressed. Execution continues after the `with` block. |
The common path is return False, which means the manager cleans up and does not interfere. Writing it explicitly tells readers that you considered the question. Falling off the end of the method returns None, which behaves the same way.
Do not re-raise the exception you were given
The exception is already in flight. If __exit__ returns a false value, Python re-raises it with its original traceback. Raising exc_value yourself adds a confusing extra frame to the traceback. Raise a new exception only when you mean to replace the old one, and chain it:
class Wrapped:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is not None and issubclass(exc_type, KeyError):
raise RuntimeError("lookup failed inside Wrapped") from exc_value
return False
try:
with Wrapped():
{}["missing"]
except RuntimeError as err:
print(err, "| caused by", repr(err.__cause__))If an exception occurs inside __exit__ itself, it replaces the original one. Python keeps the original as __context__. Cleanup code should therefore be simple and should not fail often.
A manager that decides: transaction handling
A good use of __exit__ is to behave differently on success and failure. This manager commits a database transaction if the block succeeds and rolls it back if the block raises:
import sqlite3
class Transaction:
def __init__(self, connection):
self.connection = connection
self.cursor = None
def __enter__(self):
self.cursor = self.connection.cursor()
return self.cursor
def __exit__(self, exc_type, exc_value, traceback):
self.cursor.close()
if exc_type is None:
self.connection.commit()
else:
self.connection.rollback()
return False # the caller still sees the error
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE items (name TEXT)")
with Transaction(conn) as cur:
cur.execute("INSERT INTO items VALUES ('kept')")
try:
with Transaction(conn) as cur:
cur.execute("INSERT INTO items VALUES ('discarded')")
raise ValueError("something went wrong")
except ValueError:
pass
print(conn.execute("SELECT name FROM items").fetchall())The output is [('kept',)]. The second insert was rolled back, and the ValueError still reached the try/except outside. Rolling back and returning False is the usual pairing: the manager repairs state and leaves error reporting to the caller.
Suppressing exceptions deliberately
Returning a true value tells Python "I handled this." Do that only for exception types you name explicitly:
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 clean exit exc_type is None, and issubclass(None, ...) raises TypeError. The expression also evaluates to a plain bool, which keeps the return value unambiguous. Any exception that is not a KeyError gives False and propagates. The standard library ships this as contextlib.suppress, covered in a later chapter.
When `__enter__` fails
If __enter__ raises, Python does not call __exit__. The with statement only guarantees cleanup once setup has succeeded. A manager that acquires two resources in __enter__ must therefore clean up the first one itself if the second fails:
class Pair:
def __init__(self, fail_second=False):
self.fail_second = fail_second
def __enter__(self):
print("acquire first")
try:
print("acquire second")
if self.fail_second:
raise OSError("second resource unavailable")
except BaseException:
print("release first (cleanup inside __enter__)")
raise
return self
def __exit__(self, exc_type, exc_value, traceback):
print("release second")
print("release first")
return False
try:
with Pair(fail_second=True):
print("body")
except OSError as err:
print("caught:", err)The body never runs and __exit__ never prints. The only release message comes from the handler inside __enter__. Catching BaseException and re-raising with a bare raise cleans up on any failure without changing the error.
Keeping state on the instance
The examples above store values such as self.start and self.cursor on the instance. That works, but it means one instance holds the state of one with block at a time. Using the same instance in two blocks at once, or inside itself, can overwrite that state. A later chapter treats single-use, reusable, and reentrant managers properly. For now, follow one habit: create the manager in the with line, as in with Timer() as t:, and do not store it in a variable that several blocks share.
Where the constructor and __enter__ split the work, put cheap argument storage in __init__ and the real acquisition in __enter__. Creating the object should not open files or connections. Otherwise an object created but never used leaks a resource, because no __exit__ will ever run for it.
Common mistakes
- Forgetting
return selfor the resource in__enter__. The block then fails withAttributeError: 'NoneType' object has no attribute ..., which points at the body and not at the real cause. - Leaving out an argument in the signature.
def __exit__(self)fails with aTypeErrorat the end of the block, and the real error is lost behind it. Always accept all three arguments. - Returning a truthy value by accident.
return self.cleanup()suppresses exceptions ifcleanup()returns something true. Call the function on one line andreturn Falseon the next. - Doing setup in
__init__. The resource is acquired even when nowithstatement ever runs. - Raising from cleanup before all cleanup is done. If
__exit__releases several things, an early failure skips the rest. Wrap each step in its owntry/finally, or useExitStack, covered in a later chapter.
Exercise
Write a class Indent that increases a shared indentation level by 2 on entry and restores it on exit, even if the body raises. It must expose a method say(text) that prints the text prefixed by the current indentation, and it must not suppress exceptions. What does __enter__ return, and what does __exit__ return?
Show answer
_enter returns self so the block can call say(). exit restores the old level and returns False. class Indent: level = 0 def enter(self): Indent.level += 2 return self def exit(self, exctype, exc_value, traceback): Indent.level -= 2 return False def say(self, text): print(" " * Indent.level + text) Nested blocks work because the level is shared on the class and each exit subtracts exactly what its own entry added.
Exercise
A manager's __enter__ opens a file and then calls int(first_line), which can raise ValueError. Is __exit__ called when the conversion fails? What must __enter__ do to avoid leaking the file?
Show answer
No. If _enter raises, exit is not called. enter_ must close the file itself in an except (or try/finally) clause around the code that can fail after the file is opened, then re-raise the error.