Chapters
Python114 chapters

Exercises

Context Managers

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

Write a context manager class that prints start and end around the block.

Python
# define Section

with Section("build"):
    print("working")
Exercise 2

Write the same thing as a generator with @contextmanager.

Python
from contextlib import contextmanager

# define section

with section("build"):
    print("working")
Exercise 3

Delete a file that may not exist, ignoring only that one error.

Python
import os
# remove never-existed.txt, then print done