contextlib managers in Python
Making context managers without writing a class.
import contextlib
@contextlib.contextmanager
def tag(name):
print(f"<{name}>")
try:
yield name
finally:
print(f"</{name}>")
with tag("article") as outer:
with tag("p"):
print("hello inside")
with contextlib.suppress(FileNotFoundError):
open("missing.txt")
How it works
@contextmanagerturns a generator into awithblock.- Code before
yieldis setup; after it is teardown. suppressswallows a chosen exception quietly.
Keywords and builtins used here
asdeffinallyopenprinttagtrywithyield
The run, in numbers
- Lines
- 18
- Characters to type
- 260
- Tokens
- 77
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 46 seconds.
Step 1 of 5 in Protocols & context managers, step 15 of 53 in Pythonic Python.