typestar

contextlib's other tools in Python

suppress, redirect_stdout, ExitStack and closing.

import io
from contextlib import ExitStack, redirect_stdout, suppress
from pathlib import Path

with suppress(FileNotFoundError):
    Path("never-existed.txt").unlink()
print("still here")

buffer = io.StringIO()
with redirect_stdout(buffer):
    print("captured")
print(buffer.getvalue().strip())

Path("a.txt").write_text("a")
Path("b.txt").write_text("b")
with ExitStack() as stack:
    files = [stack.enter_context(open(name)) for name in ("a.txt", "b.txt")]
    print([f.read() for f in files])

How it works

  1. suppress is a readable empty except block.
  2. redirect_stdout captures prints from code you do not own.
  3. ExitStack manages a variable number of context managers.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
483
Tokens
139
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 76 seconds.

Type this snippet

Step 3 of 4 in Measuring & introspecting, step 37 of 41 in Domain tools.

← Previous Next →