Python Context Managers and the with Statement
What you will learn
- What the
withstatement does and why it is safer - The context manager protocol:
__enter__and__exit__ - Writing one as a class
- Writing one with
@contextmanager - Suppressing errors, and the tools in
contextlib - Using several managers in one
with
1. The problem: remembering to clean up
Some resources must be released after use: files closed, locks released, connections ended. Doing it by hand is easy to forget, and an error in the middle skips the cleanup:
f = open("demo.txt", "w")
f.write("hello\n")
f.close() # skipped if write() raised an error!
Lesson 14.3 fixed this with try / finally. The with statement does the same job in a shorter and clearer way:
with open("demo.txt") as g:
print(g.read().strip(), g.closed)
print(g.closed)
hello False
True
Inside the block the file is open (closed is False); the moment the block ends, Python closes it automatically, and the name g still refers to the (closed) file object. This works even when an error occurs:
try:
with open("demo.txt") as g:
raise RuntimeError("boom")
except RuntimeError:
print("closed after error:", g.closed)
closed after error: True
Whenever you open a resource, check if it can be used with with. Files, locks, database connections, temporary directories and many more can.
Quick check: what does `with open(name) as f:` guarantee when the block ends?
That the file is closed, whether the block ended normally or with an error.
2. What with really does
The expression after with must produce a context manager: an object with two special methods (lesson 13.7):
| Method | Called | Does |
|---|---|---|
__enter__(self) |
at the start of the block | sets up; its return value goes to the name after as |
__exit__(self, exc_type, exc, tb) |
at the end, always | cleans up; receives the error details, or None, None, None if there was no error |
So with A() as x: body is roughly:
mgr = A()
x = mgr.__enter__()
try:
body
finally:
mgr.__exit__(...) # (with the error details, if any)
3. A class-based context manager
A small class that prints tags around a block shows the order of events and the arguments of __exit__:
class Tag:
def __init__(self, name):
self.name = name
def __enter__(self):
print(f"<{self.name}>")
return self
def __exit__(self, exc_type, exc, tb):
print(f"</{self.name}>", "error:" if exc_type else "ok", exc_type.__name__ if exc_type else "")
return False
with Tag("b") as t:
print("inside", t.name)
try:
with Tag("i"):
1 / 0
except ZeroDivisionError:
print("error went on")
<b>
inside b
</b> ok
<i>
</i> error: ZeroDivisionError
error went on
- When there is no error,
exc_type,excandtbare allNone. - When there is an error, they hold the type, the exception object and the traceback.
__exit__runs in both cases, so put the cleanup there.
Return value of exit: suppressing errors
If __exit__ returns a true value, the error is swallowed: the program continues after the with block as if nothing happened. If it returns False or None, the error continues upward (as with Tag above):
class Quiet:
def __enter__(self):
return self
def __exit__(self, et, e, tb):
return et is ValueError # swallow only ValueError
with Quiet():
int("x")
print("ValueError swallowed")
ValueError swallowed
Swallow errors rarely and narrowly, and only the ones you name.
4. A generator-based manager: @contextmanager
Writing a class is a lot of code for a simple job. The contextlib.contextmanager decorator lets you write a generator function (lesson 12.5) instead. Everything before yield is the setup, the yielded value goes to as, and everything after yield is the cleanup:
from contextlib import contextmanager
@contextmanager
def tag(name):
print(f"<{name}>")
try:
yield name.upper()
finally:
print(f"</{name}>")
with tag("p") as up:
print("inside", up)
try:
with tag("q"):
raise KeyError("k")
except KeyError:
print("propagated")
<p>
inside P
</p>
<q>
</q>
propagated
Put the yield inside try / finally, so the cleanup runs even when the block raises (the error is re-raised at the yield). A timer is a typical use:
import time
@contextmanager
def timer(label):
start = time.perf_counter()
try:
yield
finally:
print(label, "took", "fast" if time.perf_counter() - start < 1 else "slow")
with timer("sum"):
sum(range(1000))
sum took fast
(A real timer would print the number of seconds; it is hidden here because it changes on every run.)
5. Tools in contextlib and the standard library
A few ready-made managers:
import io
import os
from contextlib import suppress, redirect_stdout
with suppress(FileNotFoundError):
os.remove("nope.txt")
print("suppress ok")
buf = io.StringIO()
with redirect_stdout(buf):
print("captured")
print(repr(buf.getvalue()))
suppress ok
'captured\n'
suppress(ErrorType)ignores that error type for the block; a tidy replacement fortry/except/pass.redirect_stdout(target)sendsprintoutput elsewhere (useful in tests).- Locks (
with lock:, lesson 20.2), database connections and temporary directories work as context managers too. decimal.localcontext()changes number precision just inside the block:
from decimal import localcontext, Decimal
with localcontext() as ctx:
ctx.prec = 4
print(Decimal(1) / Decimal(7))
print(Decimal(1) / Decimal(7))
0.1429
0.1428571428571428571428571429
The temporary setting is restored automatically at the end of the block: that is the heart of the idea.
6. Several managers at once
Separate managers with commas, or put them in parentheses (allowed in Python 3.10 and later) for neat line breaks. They are closed in reverse order:
with open("a.txt", "w") as a, open("b.txt", "w") as b:
a.write("A")
b.write("B")
print(a.closed, b.closed)
with (
open("a.txt") as a,
open("b.txt") as b,
):
print(a.read() + b.read())
True True
AB
7. When to write your own
Write a context manager when code has a "set up, do something, always tear down" shape:
| Situation | Example |
|---|---|
| acquire and release | locks, connections, files |
| change and restore a setting | the working folder, precision, an environment variable |
| measure around a block | a timer |
| all or nothing | a transaction that commits or rolls back |
Worked example: a transaction with rollback
Money moves between accounts held in a dictionary. If anything goes wrong in the middle, every change is undone; otherwise the changes are kept. First as a class, then in the shorter @contextmanager form.
from contextlib import contextmanager
import copy
class Transaction:
"""Change a dictionary; undo every change if an error happens."""
def __init__(self, data):
self.data = data
def __enter__(self):
self.backup = copy.deepcopy(self.data)
return self.data
def __exit__(self, exc_type, exc, tb):
if exc_type is not None:
self.data.clear()
self.data.update(self.backup)
print(f"rolled back after {exc_type.__name__}: {exc}")
else:
print("committed")
return False
accounts = {"Rina": 100, "Sam": 50}
with Transaction(accounts) as acc:
acc["Rina"] -= 30
acc["Sam"] += 30
print(accounts)
try:
with Transaction(accounts) as acc:
acc["Rina"] -= 500
if acc["Rina"] < 0:
raise ValueError("overdrawn")
acc["Sam"] += 500
except ValueError:
print("caught outside")
print(accounts)
@contextmanager
def transaction(data):
backup = copy.deepcopy(data)
try:
yield data
except Exception:
data.clear()
data.update(backup)
raise
accounts2 = {"x": 1}
try:
with transaction(accounts2) as d:
d["x"] = 99
raise RuntimeError("fail")
except RuntimeError:
print(accounts2)
committed
{'Rina': 70, 'Sam': 80}
rolled back after ValueError: overdrawn
caught outside
{'Rina': 70, 'Sam': 80}
{'x': 1}
| Part | What it shows |
|---|---|
__enter__ |
takes a deep copy (lesson 7.5) as the backup and hands out the data |
__exit__ with an error |
restores the backup; returns False, so the error still propagates |
| the second transaction | the half-finished change to Rina is undone |
transaction with @contextmanager |
the same behaviour in about half the code; raise re-raises after the rollback |
The names and amounts are made up.
Common mistakes
- Opening files without
withand forgetting to close them. - Using the resource after the block (the file is closed; locks are released).
- Forgetting
try/finallyaroundyieldin a@contextmanager, so cleanup is skipped on errors. - Returning
Truefrom__exit__by accident, which hides all errors. - Swallowing errors broadly (
suppress(Exception)). - Yielding more than once in a
@contextmanagerfunction. - Putting setup that might fail in
__exit__, instead of in__enter__.
Key takeaways
withguarantees cleanup when the block ends, even after an error.- A context manager has
__enter__(setup, value foras) and__exit__(cleanup; receives error details; a true return value swallows the error). @contextmanagerturns a generator with oneyieldinto a context manager; put theyieldintry/finally.contextlib.suppress,redirect_stdoutand friends cover common cases.- Several managers can share one
with, closing in reverse order.
Practice
1. What is the advantage of with open(...) as f over calling f.close() yourself?
Show answer
The file is closed automatically, even if an error happens inside the block.
2. What are the three arguments of __exit__?
Show answer
The exception type, the exception object and the traceback (all None if the block had no error).
3. What does it mean when __exit__ returns True?
Show answer
The exception is suppressed: the program continues after the with block.
4. In a @contextmanager function, what does the code after yield do?
Show answer
It is the cleanup, run when the with block ends (put it in a finally so it runs after errors too).
5. Replace this with with:
try:
os.remove(path)
except FileNotFoundError:
pass
Show answer
from contextlib import suppress
with suppress(FileNotFoundError):
os.remove(path)
6. In which order are a and b closed in with open(x) as a, open(y) as b:?
Show answer
Reverse order: b first, then a.