Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Python as a system
EXPERIMENT 40 / 101

Leave the workbench clean.

Pair setup with cleanup so failures do not leak resources.

ADVANCED LAB
BY NAVAN SAMI◷ 11 MIN READPYTHON 3

01 The idea

A context manager defines the work to do when entering and leaving a with block. contextlib.contextmanager lets you describe that pair with a generator that yields once. Put cleanup in finally so it runs when the caller finishes normally or raises an exception. This pattern is useful for files, temporary directories, database resources, and application-level scopes.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

context_managers.py
from contextlib import contextmanager

@contextmanager
def session(name):
    print(f"open {name}")
    try:
        yield {"name": name}
    finally:
        print(f"close {name}")

with session("Orbit") as current:
    print(current["name"])
↳ EXPECTED OUTPUT
open Orbit
Orbit
close Orbit

03 Under the hood

  1. 1

    Entering the with block advances the generator to yield. The yielded value becomes current.

  2. 2

    Leaving resumes the generator, which executes finally. An exception inside the block is delivered back at the yield point.

  3. 3

    Do not swallow an exception accidentally. Catch only failures the manager can intentionally handle; otherwise let them propagate after cleanup. A context manager controls resource lifetime, not automatic transactional correctness.

04 Your turn, builder

A SMALL MISSION

Create a scope that appends "opened" and "closed" to a list even when its body raises ValueError.

Reveal one possible solution +
one_possible_solution.py
from contextlib import contextmanager
steps = []
@contextmanager
def scope():
    steps.append("opened")
    try:
        yield
    finally:
        steps.append("closed")
try:
    with scope():
        raise ValueError("practice")
except ValueError:
    pass
print(steps)

05 Check your signal

QUICK SIGNAL CHECK

Where should unconditional cleanup live?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.