typestar

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

  1. @contextmanager turns a generator into a with block.
  2. Code before yield is setup; after it is teardown.
  3. suppress swallows a chosen exception quietly.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 5 in Protocols & context managers, step 15 of 53 in Pythonic Python.

← Previous Next →