Exercises
Context Managers
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Write a context manager class that prints start and end around the block.
Python
# define Section
with Section("build"):
print("working")__enter__ and __exit__, and __exit__ should return False.
class Section:
def __init__(self, name):
self.name = name
def __enter__(self):
print("start", self.name)
return self
def __exit__(self, exc_type, exc, tb):
print("end", self.name)
return False
with Section("build"):
print("working")Exercise 2Passed
Write the same thing as a generator with @contextmanager.
Python
from contextlib import contextmanager
# define section
with section("build"):
print("working")Everything before the yield is setup; wrap the yield in try/finally.
from contextlib import contextmanager
@contextmanager
def section(name):
print("start", name)
try:
yield
finally:
print("end", name)
with section("build"):
print("working")Exercise 3Passed
Delete a file that may not exist, ignoring only that one error.
Python
import os
# remove never-existed.txt, then print done
contextlib has something tidier than try/except/pass.
import os
from contextlib import suppress
with suppress(FileNotFoundError):
os.remove("never-existed.txt")
print("done")