Context managers · 4 / 15 Theory

contextlib utilities

Besides @contextmanager, the contextlib module includes ready-made managers for very common situations. Knowing them avoids writing repeated code.

suppress: ignoring a specific error

suppress(Error) does the same as try/except Error: pass, but in one line and makes clear which error you are ignoring.

from contextlib import suppress

data = ["10", "x", "5", "2.5"]
total = 0
for text in data:
    with suppress(ValueError):
        total += int(text)
print(total)   # 15

values = {"a": 1}
with suppress(KeyError):
    del values["z"]      # does not exist: ignored
print(values)   # {'a': 1}

Use suppress only when ignoring the error is really correct. You practise it with Ignore errors.

redirect_stdout: capturing what print prints

redirect_stdout(target) sends elsewhere everything printed inside the block. With an io.StringIO you can keep that text in a variable.

import io
from contextlib import redirect_stdout

buffer = io.StringIO()
with redirect_stdout(buffer):
    print("hello")
    print("world")

text = buffer.getvalue()
print(repr(text))   # 'hello\nworld\n'
print(len(text))    # 12

Outside the block, the output goes back to the screen. It is very useful for testing functions that print. Practise it with Capture the output.

ExitStack: a variable number of managers

A with opens a fixed number of resources. If you do not know how many you will need (for example, it depends on a list), ExitStack is a stack to which you add managers with enter_context. On leaving the block they are all closed, in reverse order.

from contextlib import ExitStack, contextmanager

@contextmanager
def resource(name):
    print("open", name)
    try:
        yield name
    finally:
        print("close", name)

names = ["a", "b", "c"]
with ExitStack() as stack:
    opened = [stack.enter_context(resource(n)) for n in names]
    print("using", opened)
# open a
# open b
# open c
# using ['a', 'b', 'c']
# close c
# close b
# close a

You practise it with Resource stack.

nullcontext: a manager that does nothing

Sometimes a block must use a manager only in certain cases. nullcontext is an empty manager that lets you write a single with.

from contextlib import nullcontext, redirect_stdout
import io

def show(text, silent):
    buffer = io.StringIO()
    context = redirect_stdout(buffer) if silent else nullcontext()
    with context:
        print(text)
    return buffer.getvalue()

print(repr(show("hello", True)))    # 'hello\n'  (captured)
print(repr(show("hello", False)))   # ''  (it was printed on the screen)

closing

closing(object) calls object.close() on exit, for objects that have close() but are not context managers.

from contextlib import closing

class Connection:
    def close(self):
        print("connection closed")

with closing(Connection()) as c:
    print("using the connection")
# using the connection
# connection closed