Sub topic 5
Writing a Context Manager as a Class
This chapter assumes you know Python classes and methods, how try/except/finally works, and the basics of the with statement and the __enter__/__exit__ protocol. Here you will turn that protocol into working classes, decide what __enter__ should return, and choose between letting an exception propagate and suppressing it.
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 or raised an exception.
Python looks these methods up on the class of the object, not on the instance. Assigning obj.__enter__ = ... on an instance has no effect on with.
Example: a timer
The first manager measures how long a block takes. It needs state before the block (the start time) and after it (the elapsed time), so a class fits well.
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")__enter__ returns self, so t refers to the same Timer object. After the block, t.elapsed is available because __exit__ stored it. The timing is recorded even when the body raises, and the exception still reaches the caller because __exit__ returns False.
What `__exit__` receives
If the block ends normally, all three arguments are None. If it raises, they describe the exception:
| Argument | Meaning |
|---|---|
| `exc_type` | The exception class, such as `KeyError`, or `None` |
| `exc_value` | The exception instance, or `None` |
| `traceback` | The traceback object, or `None` |
The return value decides what happens next:
- A falsy value (
False,None, or noreturn) lets the exception continue to propagate. - A truthy value tells Python the exception was handled. Execution continues after the
withblock.
Forgetting a return statement is safe, because the implicit None means "do not suppress".
Example: suppressing selected exceptions
The next manager swallows only the exception types you list. Everything else still propagates.
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")Note the exc_type is not None check. Without it, issubclass(None, ...) raises TypeError on every normal exit. The __init__ method stores configuration, which is the usual place for arguments, while __enter__ does the actual setup.
Design guidelines
- Keep
__init__cheap. Acquire the resource in__enter__, so that merely creating the object has no side effects. - Make
__exit__robust. It runs during error handling, so avoid raising a new exception from it unless cleanup truly failed. A new exception replaces the original one, although Python keeps the original in__context__. - Do not re-raise the received exception from
__exit__. Return a falsy value and Python propagates it with its original traceback. - Return
selffrom__enter__when callers need the manager's attributes, as withTimer. Return the resource itself when the manager wraps one, asopen()does with the file.
Common errors
- Wrong signature.
__exit__must accept three arguments afterself. Defining it with none raisesTypeErrorat the end of the block. - Returning a truthy value by accident. An expression such as
return self.closedmay be truthy and silently hide errors. - Using the wrong name in
as. If__enter__returns nothing,as xbindsNone.
Exercises
Exercise
A class defines __enter__ and __exit__, and __exit__ ends with return True. What happens when the with body raises ValueError?
Show answer
The ValueError is suppressed. Python treats the truthy return value as "handled", so execution continues after the with block. This hides every exception type, not only ValueError, which is why returning True unconditionally is risky.
Exercise
Write a class Indent whose __enter__ increases a class-level counter level by 1 and whose __exit__ decreases it by 1, even if the body raises. Should __exit__ suppress exceptions?
Show answer
class Indent: level = 0 def _enter(self): Indent.level += 1 return self def exit(self, exctype, excvalue, traceback): Indent.level -= 1 return False `exit_` should not suppress exceptions. It only restores state, so errors from the body must still reach the caller.