Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 9.8 — Writing Context Managers with contextlib
Python · Example 2 of 3

ExitStack, closing and redirect_stdout

Add a third file name to the list. ExitStack closes however many you open.

contextlib lets you write your own with blocks using a generator and @contextmanager, and gives tools for common jobs: suppress to ignore an error, ExitStack to manage a changing number of resources, closing, redirect_stdout and nullcontext.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a @contextmanager named banner(title) that prints === title === before the block and === end === after it (in finally). Use it around one print.

02

Use suppress so that deleting a missing key from a dictionary does not raise: del data["zzz"], then print data.

03

Write a @contextmanager named temporary_value(box, key, value) that sets box[key] = value for the block and restores the old value afterwards. Show the dictionary before, inside and after.

Explain it without notes

01

What does the with statement guarantee, and how do __enter__ and __exit__ fit in?

02

How does @contextmanager turn a generator into a context manager, and what must you do around the yield?

03

When would you use ExitStack?

04

What do suppress, nullcontext and closing each do?

ExitStack, closing and redirect_stdout
Sign in to run this example in your browser.

Expected output

['one', 'two']
cleanup callback ran
all closed: True
using connection
connection closed
captured: 'this goes into the buffer\n'