Sub topic 13
Pitfalls and How to Test Context Managers
What this chapter assumes
You should know how with calls __enter__ and __exit__, how __exit__ receives exception information, and how @contextmanager turns a generator into a manager. You should also be comfortable with pytest basics. This chapter collects the mistakes that come up most often and shows how to write tests that catch them.
How an exception travels through a manager
Most pitfalls come from one question: what happens to an exception raised inside the with body? The diagram shows the decision points.
Each pitfall below is a wrong turn at one of these three branches.
Pitfalls
Missing try/finally around yield
In a generator-based manager, an exception in the with body is thrown into the generator at the yield line. Code after the yield runs only if no exception arrives.
from contextlib import contextmanager
events = []
@contextmanager
def broken():
events.append("open")
yield
events.append("close") # skipped when the body raises
try:
with broken():
raise ValueError("boom")
except ValueError:
pass
print(events) # ['open']The resource is never released. Wrap the yield in try/finally, and put every cleanup step in the finally block.
Accidentally suppressing exceptions in __exit__
Python checks only the truthiness of the value __exit__ returns. A method that ends with return self.cleanup() can swallow every exception if cleanup() returns something truthy.
class Leaky:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
return self.cleanup() # True here, so errors vanish
def cleanup(self):
print("cleaning")
return True
with Leaky():
raise RuntimeError("this error disappears")
print("still running")Return False or None unless you mean to suppress. When you do suppress, restrict it to specific exception types, as the Ignore manager from the earlier chapter does.
Catching without re-raising in a generator
A generator-based manager suppresses an exception if it catches it and finishes normally. This is the generator version of the same mistake.
from contextlib import contextmanager
@contextmanager
def quiet():
try:
yield
except Exception as error:
print("logged:", error) # no raise, so the error is swallowed
with quiet():
1 / 0
print("execution continues")If you only want to log, add a bare raise after the print. If you want to translate the error, raise a different exception with raise NewError(...) from error.
Raising from cleanup hides the original error
If __exit__ (or a finally block) raises, the new exception replaces the one in flight. Python keeps the old one in __context__, so it is not lost, but the traceback now leads with the cleanup failure.
class BadCleanup:
def __enter__(self):
return self
def __exit__(self, *exc_info):
raise OSError("cleanup failed")
try:
with BadCleanup():
raise ValueError("original")
except OSError as error:
print(repr(error), "| context:", repr(error.__context__))
# OSError('cleanup failed') | context: ValueError('original')Keep cleanup code simple. If it can fail, decide whether the cleanup error or the body error matters more, and handle the other one deliberately (for example, log it).
Forgetting to return a value from __enter__
The as target receives whatever __enter__ returns. A method with no return gives you None.
class Connection:
def __enter__(self):
self.open = True # no return statement
def __exit__(self, *exc_info):
self.open = False
with Connection() as conn:
print(conn) # NoneReturn self unless the as target should be something else, such as a file handle or a path.
Reusing a single-use manager
A manager made by @contextmanager wraps one generator, and a generator can run only once. Entering the same object a second time fails.
from contextlib import contextmanager
@contextmanager
def tag(name):
print(f"<{name}>")
yield
print(f"</{name}>")
cm = tag("p")
with cm:
pass
try:
with cm:
pass
except RuntimeError as error:
print(error) # generator didn't yieldCall the function again for each with (with tag("p"):). File objects are single-use for a similar reason: after the first block closes the file, a second with f: raises ValueError: I/O operation on closed file. If you need an object that can be entered repeatedly, write a class whose __enter__ creates fresh state each time. Reentrancy (entering while already inside) needs more care, such as a depth counter.
Using the resource after the block
The as variable stays alive after the with block, but the resource behind it is closed. This bites hardest with lazy values.
def read_lines(path):
with open(path) as f:
return (line.strip() for line in f) # lazy generator
lines = read_lines("data.txt")
# next(lines) raises ValueError: I/O operation on closed fileEither consume the data inside the block (return [line.strip() for line in f]) or make the function itself a generator that holds the with open while it yields.
More than one yield
A @contextmanager generator must yield exactly once. A second yield (for example, inside a loop) raises RuntimeError: generator didn't stop. If you need several resources in sequence, nest with statements inside the generator or use ExitStack.
Testing context managers
A manager makes four promises: setup runs, cleanup runs on every exit path, exceptions propagate unless suppression is intended, and the as value is correct. Tests should check each one. The easiest approach is to give the manager a log and assert on what happened, in order.
# managed.py
from contextlib import contextmanager
@contextmanager
def managed(log, name):
log.append(f"open {name}")
try:
yield name
finally:
log.append(f"close {name}")
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):
return exc_type is not None and issubclass(exc_type, self.exc_types)# test_managed.py
import pytest
from managed import Ignore, managed
def test_setup_and_cleanup_on_success():
log = []
with managed(log, "a") as name:
assert name == "a"
assert log == ["open a"] # setup ran before the body
assert log == ["open a", "close a"]
def test_cleanup_runs_and_error_propagates():
log = []
with pytest.raises(ValueError, match="boom"):
with managed(log, "a"):
raise ValueError("boom")
assert log == ["open a", "close a"]
def test_single_use():
cm = managed([], "a")
with cm:
pass
with pytest.raises(RuntimeError):
with cm:
pass
def test_ignore_suppresses_only_listed_types():
with Ignore(KeyError):
{}["missing"] # suppressed
with pytest.raises(ValueError):
with Ignore(KeyError):
raise ValueError("not listed")
def test_exit_return_values_directly():
cm = Ignore(KeyError)
assert cm.__exit__(KeyError, KeyError("x"), None) is True
assert cm.__exit__(ValueError, ValueError("x"), None) is False
assert cm.__exit__(None, None, None) is FalseNotice the pattern in test_cleanup_runs_and_error_propagates. The pytest.raises block goes outside the with under test, so the test fails if the exception is accidentally swallowed. The assertion on log goes after it, so it proves cleanup ran even though the body failed.
Calling __exit__ directly, as in the last test, is useful for checking return values on each branch without building a with block. It is a white-box check, so use it for suppression logic and keep the other tests on the real with syntax.
Testing code that uses a manager
When the function under test opens a real resource, replace the resource with a MagicMock. MagicMock supports the context manager protocol, and its __exit__ returns a falsy value by default, so exceptions still propagate.
from unittest.mock import MagicMock
def write_report(opener, text):
with opener("report.txt", "w") as f:
f.write(text)
def test_write_report_writes_and_closes():
opener = MagicMock()
write_report(opener, "hi")
handle = opener.return_value
handle.__enter__.return_value.write.assert_called_once_with("hi")
handle.__exit__.assert_called_once_with(None, None, None)The (None, None, None) arguments confirm the block ended normally. In a failure test, you would assert that __exit__ received the exception type as its first argument. Passing the opener as a parameter keeps the test free of patching. For real files, pytest's tmp_path fixture is often simpler and tests more of the real behavior.
Quick checklist
| Check | What to look for |
|---|---|
| Generator managers | `yield` sits inside `try`, and cleanup is in `finally` |
| `__exit__` return value | `False` or `None`, unless suppression is deliberate and limited to named types |
| `__enter__` return value | Returns `self` or the intended resource |
| Reuse | One manager object per `with`, or a class that rebuilds its state |
| Lifetime | Nothing lazy escapes the block |
| Tests | Success, body error, and cleanup-order assertions |
Practice
Exercise
This manager is meant to restore a global setting after the block. Name two bugs in it. @contextmanager def verbose(): global LEVEL old = LEVEL LEVEL = "debug" try: yield except Exception: print("failed") LEVEL = old
Show answer
First, the except branch catches the exception and never re-raises it, so every Exception raised in the body is suppressed. Second, LEVEL = old sits after the try/except instead of in a finally block. A BaseException that is not an Exception, such as KeyboardInterrupt, skips the restore, and so does any exception raised inside the except handler. The fix is to use try: yield with finally: LEVEL = old, and to add raise after the print if logging is still wanted.
Exercise
Write a pytest test that proves a manager named locked(lock) releases the lock even when the body raises a RuntimeError, and that the RuntimeError is not swallowed. Which two things must the test assert?
Show answer
Wrap the with locked(lock): block, whose body raises RuntimeError, inside with pytest.raises(RuntimeError):. This asserts that the exception propagates. After the pytest.raises block, assert that the lock is released (for example, assert not lock.locked() for a threading.Lock). Placing the lock assertion outside the pytest.raises block ensures it runs after the failure has passed through the manager.