with: always clean up
🌍 In real life. You borrow a book from the library, read it, and give it back. But what if you spill tea on it halfway through? You still have to return the book. Good habits make sure the clean-up step always happens, whatever goes wrong in the middle.
Programs borrow things too: an open file, a network connection, a lock. A with block makes the clean-up automatic:
- on the way in, a setup step runs (open the file, borrow the book)
- then your block runs
- on the way out, a clean-up step runs (close the file, return the book), even if the block raised an error
The idea in one sentence: with something as name: sets something up, runs the block, and always cleans up at the end, even if the block raises an error.
Its words:
- context manager: an object that knows how to set up and clean up, like an open file
- clean-up: the step that must always happen, like closing a file
try/finally: whatwithdoes for you behind the scenes
You met with in Chapter 20 for files. Here is why it's better than calling close() yourself, step by step:
- with plain
openandclose, an error beforeclose()means your code never closes the file, and what you wrote may not be saved yet try/finallyfixes that: thefinallypart always runswith open(...) as f:does the sametry/finallywork for you, in one short line
f = open("notes.txt")
try:
print(f.readline().strip())
finally:
f.close() # always runs
print("closed?", f.closed)
with open("notes.txt") as f:
print(f.readline().strip())
print("closed?", f.closed) # with closed it for usdef borrow(spill):
print("book borrowed")
try:
print("reading")
if spill:
raise ValueError("tea spilled")
print("finished")
finally:
print("book returned")
borrow(False)
try:
borrow(True)
except ValueError as e:
print("problem:", e)Why with instead of try/finally? Both make sure clean-up happens. with puts the setup and the clean-up in one place, owned by the object that knows how to do them, so you can't forget one half, and the code reads as "while I have this file open, do this".
Mistakes and edge cases.
- with on something that isn't a context manager.
with 5 as x:givesTypeError: 'int' object does not support the context manager protocol (missed __exit__ method). - Using the resource after the block. The file is closed once the block ends.
- Expecting with to catch the error. It cleans up, then the error carries on; add
try/exceptif you want to handle it.
Quiz
What does this print?
try: print("start") x = 1 / 0 print("never") except ZeroDivisionError: print("caught") finally: print("clean up")When does the clean-up of a
withblock run?- Every time the block ends, even after an error
- Only if the block finishes without an error
- Only when you call close()
What does this print?
with open("a.txt", "w") as f: f.write("hi") print(f.closed)What does this print?
def lend(): try: return "lent" finally: print("returned") print(lend())Which line has a mistake? (The file should be read inside the with block.)
with open("a.txt", "w") as f: f.write("hello") with open("a.txt") as f: pass print(f.read())
Coding tasks
Write
first_line(name)that returns the first line of the file, without its newline. Usewith.Write
log_lines(name, lines)that adds each line (with a newline) to the end of the file, then reads the file back and returns how many lines it has now. Close the file before reading it back, or the new lines may not be saved yet.Write
run_safely(func): callfunc(); return"ok"if it works, or"error"if it raises a ValueError. Either way, append"cleaned up"to the listlog.