Sub topic 9
Useful tools in contextlib
The contextlib module in the standard library holds ready-made context managers for jobs that come up again and again. Using them keeps your own code short and removes the need to write a new class each time.
This chapter assumes you know how with, __enter__ and __exit__ work, and how @contextmanager is built. Earlier chapters covered both. It also assumes you are on Python 3.11 or newer. chdir was added in that version.
Choosing a helper
Each helper replaces a pattern you would otherwise write by hand. The table lists what each one does.
| Helper | What it does | Replaces |
|---|---|---|
| `suppress(*exceptions)` | Ignores the listed exception types | `try` / `except` / `pass` |
| `closing(obj)` | Calls `obj.close()` on exit | `try` / `finally` with `close()` |
| `redirect_stdout(target)` | Sends `sys.stdout` to another file-like object | Manual swapping of `sys.stdout` |
| `redirect_stderr(target)` | Same, for `sys.stderr` | Manual swapping of `sys.stderr` |
| `nullcontext(value)` | Does nothing and returns `value` | Duplicated code with and without a manager |
| `chdir(path)` | Changes the working directory, then restores it | A hand-written `working_directory` manager |
The diagram shows how to choose between them.
suppress: ignore specific exceptions
suppress takes one or more exception types. If the body raises one of them, the exception is discarded and execution continues after the with block.
from contextlib import suppress
import os
with suppress(FileNotFoundError):
os.remove("maybe-missing.tmp")
print("done")This is equivalent to the following code, but shorter and easier to scan.
import os
try:
os.remove("maybe-missing.tmp")
except FileNotFoundError:
pass
print("done")suppress is the Ignore class from the earlier chapter, already written and tested.
What suppress does not do
- It does not resume the body. When the exception is raised, the rest of the block is skipped.
- It matches by
issubclass, sosuppress(OSError)also hidesFileNotFoundErrorandPermissionError. Name the narrowest type you can. - It cannot log or inspect the exception. If you need either, use
try/except.
from contextlib import suppress
data = {"a": 1}
with suppress(KeyError):
print(data["a"])
print(data["b"]) # raises KeyError, so the rest is skipped
print("never reached")
print("after the block")The output is 1 and then after the block.
closing: make close() work with with
Some objects have a close() method but no __enter__ or __exit__. closing(obj) wraps such an object. On exit it calls obj.close(), and on entry it returns the object itself.
from contextlib import closing
class Connection:
def __init__(self, name):
self.name = name
print(f"open {self.name}")
def query(self, sql):
return f"{self.name}: {sql}"
def close(self):
print(f"close {self.name}")
with closing(Connection("db")) as conn:
print(conn.query("SELECT 1"))The output is open db, db: SELECT 1, then close db. The close call runs even if the body raises. closing is written as a small @contextmanager function with try / finally, which you already know how to build.
Many modern objects, including files and sockets, are already context managers. Use closing only for objects that lack __exit__. Check by trying a plain with first.
redirect_stdout and redirect_stderr: capture output
redirect_stdout(target) replaces sys.stdout with target for the length of the block, then restores the original. The target is any object with a write() method. This is useful when a function prints and you want the text as a string.
import io
from contextlib import redirect_stdout
buffer = io.StringIO()
with redirect_stdout(buffer):
print("captured")
print(repr(buffer.getvalue()))This prints 'captured\n'. The first print wrote into the buffer, and the second one wrote to the real console because the block had ended.
You can also redirect to a file.
from contextlib import redirect_stdout
with open("report.txt", "w") as f, redirect_stdout(f):
print("this line goes to report.txt")redirect_stderr works the same way for error output. The two can be combined in one with statement.
Limits of redirection
- It changes the global
sys.stdout, so it affects every thread. It is not safe in concurrent code. - It only affects code that writes through
sys.stdout. Child processes and C extensions that write to the operating system's file descriptor 1 are not captured. - It is not a logging tool. For lasting output, use the
loggingmodule.
nullcontext: a manager that does nothing
nullcontext(value=None) enters without doing anything, returns value from __enter__, and does nothing on exit. Its job is to make a manager optional without repeating the body of the with block.
Suppose a function accepts either a path or an already open file. You want to close files you opened, and leave caller-owned files alone.
import io
from contextlib import nullcontext
def read_text(source):
if isinstance(source, str):
manager = open(source) # we own it, so close it
else:
manager = nullcontext(source) # caller owns it, so leave it open
with manager as f:
return f.read()
stream = io.StringIO("hello")
print(read_text(stream))
print(stream.closed)The output is hello and then False. The with statement is written once, and only the choice of manager varies.
The same trick works for optional locking.
import threading
from contextlib import nullcontext
def make_counter(thread_safe):
lock = threading.Lock() if thread_safe else nullcontext()
count = 0
def increment():
nonlocal count
with lock:
count += 1
return count
return increment
counter = make_counter(thread_safe=False)
print(counter(), counter())This prints 1 2.
chdir: temporarily change directory
In Python 3.11 and later, contextlib.chdir(path) does what the working_directory example in an earlier chapter did. It changes the current directory on entry and restores the previous one on exit, even when the body raises.
import os
import tempfile
from contextlib import chdir
before = os.getcwd()
with tempfile.TemporaryDirectory() as tmp:
with chdir(tmp):
print(os.getcwd() == os.path.realpath(tmp))
print(os.getcwd() == before)Both lines print True. We compare against os.path.realpath because some systems, such as macOS, report temporary directories through a symbolic link. Like redirect_stdout, chdir changes process-wide state, so avoid it in multithreaded programs.
Using a manager as a decorator
Managers built with @contextmanager or by subclassing ContextDecorator can also be applied as decorators. The manager then wraps each call of the function.
from contextlib import contextmanager
@contextmanager
def announce(label):
print(f"start {label}")
try:
yield
finally:
print(f"end {label}")
@announce("job")
def work():
print("working")
work()
work()The output is start job, working, end job, repeated twice. Each call gets a fresh run of the generator, so decorating a function is safe. This works only for managers that do not need the as value, because a decorator has no place to put it.
Other helpers worth knowing
aclosing(obj)is the asynchronous version ofclosing. It awaitsobj.aclose()and is the standard way to guarantee that an async generator is cleaned up.AbstractContextManageris a base class. It supplies__enter__(which returnsself) so you only write__exit__.ExitStack, covered in the next chapters, manages a variable number of managers.
Exercises
Exercise
A function parses a config file and should treat a missing file as an empty config. A colleague wraps the whole 40-line function body in with suppress(OSError):. Give two problems with this and write a better version of the file-reading part.
Show answer
First, OSError also covers PermissionError and IsADirectoryError, so real problems are hidden. Second, any OSError anywhere in the 40 lines silently skips the rest of the function, which makes bugs hard to find. A better version narrows both the type and the body:
from contextlib import suppress
def load(path):
text = ""
with suppress(FileNotFoundError):
with open(path) as f:
text = f.read()
return text
Exercise
Write capture(func, *args) that calls func(*args) and returns everything it printed as a string, without printing anything to the console. Then say why this would be unreliable inside a multithreaded program.
Show answer
import io
from contextlib import redirectstdout
def capture(func, *args):
buffer = io.StringIO()
with redirectstdout(buffer):
func(*args)
return buffer.getvalue()
It is unreliable with threads because redirect_stdout replaces the global sys.stdout. Output from other threads during the block also lands in the buffer, and two overlapping redirects can restore the wrong stream.
Exercise
You have def process(lines, log=None), where log may be an open file or None. You want to write with log: once, so that nothing breaks when log is None. Which helper do you use, and how?
Show answer
Use nullcontext. Write manager = log if log is not None else nullcontext(), then with manager:. Because nullcontext() does nothing on exit, a caller-supplied file is closed by its own manager and the None case runs the same code with no cleanup. If you need the file inside the block, write with manager as f:. Note that nullcontext() returns None as the as value in that case, so guard writes with if f is not None.