Sub topic 13
Replacing try/finally with context managers
This chapter assumes you can write try/except/finally, define functions and classes, and read a simple traceback. It shows how the with statement packages the cleanup pattern from the finally chapter so you don't have to repeat it.
The problem: repeated cleanup
Any resource you must release needs the same shape. Examples are a file, a lock, or a database connection.
f = open("notes.txt")
try:
first_line = f.readline()
finally:
f.close()This works, but it is easy to forget the finally, and every call site repeats it. A context manager moves that pattern into one reusable place.
The with statement
A context manager is an object that defines what happens when a block is entered and when it is left. The with statement uses it:
with open("notes.txt") as f:
first_line = f.readline()When the block ends, Python closes the file. It does this on normal completion, on return, break, or continue, and when an exception is raised inside the block. This is the same guarantee finally gives.
What happens behind the scenes
A context manager implements two methods:
__enter__()runs when the block starts. Its return value is bound to the name afteras.__exit__(exc_type, exc_value, traceback)runs when the block ends. If no exception occurred, all three arguments areNone.
If __exit__ returns a true value, the exception is suppressed. If it returns None or False, the exception continues to propagate. Return a true value only when you mean to swallow the error.
Writing one with a generator
You rarely need to write __enter__ and __exit__ by hand. The contextlib.contextmanager decorator turns a generator function into a context manager. Code before yield is the setup. The yielded value is what as receives. Code after yield is the cleanup.
from contextlib import contextmanager
@contextmanager
def opened(path):
f = open(path)
try:
yield f
finally:
f.close()
with opened("notes.txt") as f:
first_line = f.readline()The try/finally around yield is required. If the body of the with statement raises, the exception is thrown into the generator at the yield line. Without finally, the code after yield would never run.
Common errors
- Forgetting
try/finallyin a generator-based manager. The cleanup is skipped on errors. - Suppressing exceptions by accident. In a class-based manager, an
__exit__that ends withreturn Truehides every error, including bugs. - Using the resource after the block. A file closed by
withraisesValueErrorif you read from it afterward. - Opening the resource outside
with. Writingf = open(path)and thenwith f:works, but a failure between the two lines leaks the file.
You can also combine several managers in one statement:
with open("in.txt") as src, open("out.txt", "w") as dst:
dst.write(src.read())Both files are closed in reverse order, even if the write fails.
Exercise
A generator-based context manager contains yield f followed by f.close(), with no try/finally. The with body raises an exception. Does f.close() run, and why?
Show answer
No. The exception is thrown into the generator at the yield line, so the code after yield is skipped. Wrapping the yield in try/finally makes the close run on every path.
Exercise
What must _exit_ return to stop an exception from propagating out of the with block?
Show answer
A true value, such as True. Returning None or False lets the exception continue.