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
suppressis a readable empty except block.redirect_stdoutcaptures prints from code you do not own.ExitStackmanages a variable number of context managers.
Keywords and builtins used here
asforopenprintwith
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.
Step 3 of 4 in Measuring & introspecting, step 37 of 41 in Domain tools.