Sub topic 9
Useful tools in contextlib
This chapter assumes you know how with, __enter__, and __exit__ work, and that you have written a manager with @contextmanager. The contextlib module also ships ready-made managers for common jobs. Using them is shorter and less error-prone than writing your own.
suppress: ignore specific exceptions
suppress replaces a try/except/pass block. It swallows only the exception types you list. Any other exception still propagates.
from contextlib import suppress
import os
with suppress(FileNotFoundError):
os.remove("maybe-missing.tmp")
print("done")Execution leaves the with block at the first exception, so lines after the failing one inside the block do not run. Keep the block small, ideally one statement, so you do not hide errors you did not mean to ignore.
closing: call close() on objects that lack __exit__
Some objects have a close() method but are not context managers. closing(obj) wraps them so close() runs when the block ends.
from contextlib import closing
class Connection:
def query(self):
return "rows"
def close(self):
print("connection closed")
with closing(Connection()) as conn:
print(conn.query())The as clause receives the original object, not the wrapper.
redirect_stdout and redirect_stderr: capture output
redirect_stdout temporarily replaces sys.stdout. It is handy when a function prints something you want as a string, for example in a test.
import io
from contextlib import redirect_stdout
buffer = io.StringIO()
with redirect_stdout(buffer):
print("captured")
print(repr(buffer.getvalue()))The original sys.stdout is restored on exit, even if the block raises. redirect_stderr works the same way for sys.stderr. Both change a process-wide global, so they are not safe to use from several threads at once.
nullcontext: a manager that does nothing
nullcontext lets you write one with statement when a manager is optional. Without it, you would need two code paths.
from contextlib import nullcontext
def process(lines, log=None):
with log if log is not None else nullcontext():
for line in lines:
print(line.upper())
process(["a", "b"])You can also give nullcontext a value. It becomes the result of the as clause, so the code inside the block can treat real and placeholder managers the same way.
from contextlib import nullcontext
def read_first_line(source):
# source is either a path or an already open file-like object
if isinstance(source, str):
manager = open(source)
else:
manager = nullcontext(source)
with manager as f:
return f.readline()In this version, a file opened by the function is closed. A file passed in by the caller is left open, because nullcontext does nothing on exit.
Summary of the helpers
| Helper | Purpose | Value bound by `as` |
|---|---|---|
| `suppress(*types)` | Ignore listed exception types | `None` |
| `closing(obj)` | Call `obj.close()` on exit | `obj` |
| `redirect_stdout(target)` | Send `sys.stdout` to `target` | `target` |
| `redirect_stderr(target)` | Send `sys.stderr` to `target` | `target` |
| `nullcontext(value)` | Do nothing | `value` (default `None`) |
Choosing a helper
Exercise
A function accepts either a file path or an open file object. You want to close the file only when the function opened it. Which contextlib helper makes a single with statement possible, and why?
Show answer
Use nullcontext. Wrap the caller's open file as nullcontext(file) and use open(path) for a path. Both work in with ... as f, but nullcontext does nothing on exit, so the caller's file stays open.
Exercise
What is wrong with this code, and how would you fix it? with suppress(Exception): config = loadconfig() startserver(config)
Show answer
suppress(Exception) hides every error from both calls, including bugs and failed startups, so the program silently continues. Catch only the specific expected error, such as suppress(FileNotFoundError), and wrap only the call that can raise it (load_config()).