Show contents
Chapter 5 of 7 · 20 min
Context managers
By the end of this chapter, you'll be able to
- Explain what with does thanks to __enter__ and __exit__
- Write a context manager as a class
- Write a context manager with contextlib.contextmanager
- Guarantee clean-up with try/finally and ignore an error with suppress
What with does
A context manager is an object with two methods. with obj as x: calls obj.__enter__() at the start of the block (its return value becomes x), then obj.__exit__(...) at the end, whether the block ends normally or with an exception.
class Stopwatch:
def __init__(self, name):
self.name = name
def __enter__(self):
print(f"[{self.name}] start")
return self
def __exit__(self, error_type, error, trace):
state = "failure" if error_type else "success"
print(f"[{self.name}] end ({state})")
return False
with Stopwatch("import"):
print(" processing…")
try:
with Stopwatch("calculation"):
1 / 0
except ZeroDivisionError:
print("The error did propagate")
[import] start
processing…
[import] end (success)
[calculation] start
[calculation] end (failure)
The error did propagate
__exit__ receives the type, value and trace of any exception (or three Nones). If it returns False, the exception carries on; if it returns True, it's swallowed. Return False unless you have a very good reason to make the error disappear.
__exit__ returned False: the exception carries on to the enclosing try.
Text description of the animation
- with calls __enter__: the resource is acquired.
- The block raises an exception: it stops dead.
- Before the exception propagates, Python calls __exit__ with its details. The resource is released.
- __exit__ returned False: the exception carries on to the enclosing try.
Shorter: contextlib.contextmanager
Writing a class for each resource is verbose. The @contextmanager decorator turns a generator into a context manager: the code before yield plays the role of __enter__, the value produced by yield is the one bound by as, and the code after plays the role of __exit__.
from contextlib import contextmanager, suppress
@contextmanager
def transaction(account):
backup = dict(account)
try:
yield account
print("committed")
except ValueError as error:
account.clear()
account.update(backup)
print("rolled back:", error)
account = {"balance": 100}
with transaction(account) as a:
a["balance"] -= 30
print(account)
with transaction(account) as a:
a["balance"] -= 500
if a["balance"] < 0:
raise ValueError("negative balance")
print(account)
with suppress(FileNotFoundError):
open("missing.txt").read()
print("carrying on")
committed
{'balance': 70}
rolled back: negative balance
{'balance': 70}
carrying on
An exception raised in the with block reappears at the yield: the try/except around the yield can therefore catch it and undo the changes. That's the principle of a transaction: all or nothing.
suppress(FileNotFoundError) ignores one precise exception, explicitly: it's more readable than a try/except: pass.
Your turn
The booking lockPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Worked exercise
Worked exercise: changing folder temporarily
Write a context manager in_folder(path) that moves into a folder (os.chdir) for the duration of the block, then always goes back to the starting folder, even if there's an error. Test it by creating a subfolder reports, writing a file in it, then checking that the current folder is back to the original one, including after an exception.
Hint 1
os.getcwd() gives the current folder: keep it before changing.Hint 2
finally, around the yield.Show the solution and common mistakes
import os
from contextlib import contextmanager
@contextmanager
def in_folder(path):
start = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(start)
origin = os.getcwd()
os.makedirs("reports", exist_ok=True)
with in_folder("reports"):
with open("summary.txt", "w", encoding="utf-8") as f:
f.write("ok")
print(os.getcwd() == origin, os.path.exists("reports/summary.txt"))
try:
with in_folder("reports"):
raise RuntimeError("breakdown")
except RuntimeError:
pass
print(os.getcwd() == origin)
True True
True
Common mistakes:
- Putting
os.chdir(start)after theyieldwithoutfinally: after the exception, the program stays inreports, and every following relative path is wrong. - Calling
os.chdir(path)inside thetry: if the folder doesn't exist, thefinally"goes back" to the start even though we never left it. It's harmless here, but keep acquiring the resource before thetry.
Summary
- 1with calls __enter__ at the start and __exit__ at the end, even if there's an exception.
- 2An __exit__ that returns True swallows the exception: avoid it unless you mean it.
- 3@contextmanager turns a generator into a manager: before yield = entry, after = exit.
- 4A @contextmanager's clean-up goes in a finally around the yield.
- 5suppress ignores one precise exception explicitly.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.