python · level 3 · unit 3 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
turns a generator into a context manager.
A whole class is a lot of typing for set-up and clean-up. The module has a shortcut: put @contextmanager above a generator that yields exactly once.
Everything before the yield is the set-up, and whatever you yield is caught by as. Everything after the yield is the clean-up, which runs when the block ends.
Put the yield inside try and the clean-up inside finally. Then the clean-up runs even if the block crashes, as __exit__ does.
from contextlib import contextmanager
settings = {"theme": "light"}
@contextmanager
def temporary(key, value):
old = settings[key]
settings[key] = value
try:
yield settings
finally:
settings[key] = old
with temporary("theme", "dark") as s:
print("inside:", s["theme"])
print("after:", settings["theme"]) contextlib also has suppress, so with suppress(FileNotFoundError): ignores that one error inside the block.
guess first
No finally this time. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
from contextlib import contextmanager
@contextmanager
def lights():
print("lights on")
yield
print("lights off")
try:
with lights():
print("party starts")
raise ValueError("music too loud")
except ValueError:
print("party stopped")
your turn
Your turn. Group some output under a title.
Fill the first blank so the block runs at that point. In the second, give the section any title you like.
fix it
The till will not open. Fix it!
- The error says a generator cannot be used with
with. What turns one into a context manager? - The import on line 1 is there, but nothing uses it.
- Add
@contextmanageron the line abovedef opened_till():, then run.
nailed it
you built context managers the short way. :D
@contextmanagerturns a one-yieldgenerator into a context manager.- Code before
yieldsets up. Code after it cleans up. - Wrap the
yieldintryandfinallyso clean-up always runs.
new words in your collection
- contextlib
- contextmanager
This lesson isn’t saved. A free account remembers every lesson you finish.