Skip to main content
🔒 Preview mode. The first 15 Foundations lessons are free; this one is Pro. Start a 7-day trial to unlock the editor, AI hints and the rest of the curriculum. Card required, cancel any time in Dashboard.Start 7-day trial →
← CoursesSenior Deep-DivesModule 11 · Decorator patterns at scale@contextlib.contextmanager — context managers from generatorspredict154 / 161
+150 XP
Task
📝 **Task:** Predict the 11-line output. A `@contextmanager`-decorated `measure(name)` runs setup before yield and teardown after. Three with-blocks: normal use, body-raises-exception (caught outside), and the same context name reused twice (each call is a fresh generator). Pay attention to the order of `<download` vs `caught network error` — the finally branch runs BEFORE the exception escapes. 📋 Implement the function above. Tests run automatically. 💡 **Hint:** Re-read the theory if you get stuck.
Predict the output

Read the code carefully

from contextlib import contextmanager


events: list[str] = []


@contextmanager
def measure(name: str):
    events.append(f">{name}")
    try:
        yield {"name": name, "id": 42}
    finally:
        events.append(f"<{name}")


# 1. Normal use — yielded value bound to ctx
with measure("upload") as ctx:
    events.append(f"  inside: name={ctx['name']}, id={ctx['id']}")

# 2. Exception inside body — finally still runs, THEN exception escapes
try:
    with measure("download"):
        events.append("  download body")
        raise RuntimeError("network down")
except RuntimeError:
    events.append("  caught network error")

# 3. Same context name twice — each with-block creates a fresh generator
with measure("a"):
    pass
with measure("a"):
    pass

for e in events:
    print(e)

What will the program print? Write here:

💬 Discussion

Be the first to ask a question or share a tip.
Sign in to join the discussion. Reading is free.
Loading discussion…