python · level 3 · unit 3 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A sets up, then always cleans up.
You already write with open(...) as f:. The object after with is a context manager. Python calls its __enter__ method as the block starts, and its __exit__ method as the block ends, however it ends.
That is the whole trick. Even if the block crashes, __exit__ still runs, so a like a file or a lock is always given back. Whatever __enter__ returns is caught by the name after as.
Write a class with those two methods and you have your own context manager.
class Job:
def __init__(self, label):
self.label = label
def __enter__(self):
print(f"{self.label}: start")
return self
def __exit__(self, kind, error, trace):
print(f"{self.label}: tidied up")
with Job("backup") as job:
print("working on", job.label)
print("after the block") __exit__ receives three details about any error, or three Nones when nothing went wrong.
guess first
Something breaks inside the block. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class Door:
def __enter__(self):
print("door open")
def __exit__(self, kind, error, trace):
print("door shut")
try:
with Door():
print("carrying boxes")
boxes = 3 / 0
print("all done")
except ZeroDivisionError:
print("dropped a box")
your turn
Your turn. Write the clean-up half.
Fill the first blank with the name of the method that runs as the block ends. In the second, write what happens to the room afterwards.
fix it
The basket vanishes inside the block. Fix it!
- The error says
Nonehas noitems. What did the name afterascatch? - The name after
asgets whatever__enter__returns, and this__enter__returns nothing. - Add
return selfat the end of__enter__, then run.
nailed it
you know what with does behind the scenes. :D
__enter__runs as the block starts,__exit__as it ends.__exit__runs even when the block crashes.- The name after
ascatches what__enter__returns.
new words in your collection
- context manager
- resource
This lesson isn’t saved. A free account remembers every lesson you finish.