Sub topic 8
Several context managers in one with statement
This chapter assumes you can write a basic with statement, know how __enter__ and __exit__ work, and can read a class-based or @contextmanager manager. Here you will combine several managers in one with statement and see what order they run in.
Why combine managers
Many tasks need more than one resource at once. Copying a file needs a source open for reading and a destination open for writing. You could nest two with blocks:
with open("in.txt") as src:
with open("out.txt", "w") as dst:
dst.write(src.read())This works, but each extra resource adds another level of indentation. Python lets you list the managers in one statement, separated by commas.
The comma form
with open("in.txt") as src, open("out.txt", "w") as dst:
dst.write(src.read())This is defined as equivalent to the nested version. The managers are entered from left to right. They are exited in the opposite order, right to left. Each as name is available to every manager to its right, so a later manager can use an earlier one:
import json
with open("config.json") as f, open("copy.json", "w") as out:
json.dump(json.load(f), out)Entry and exit order
The order matters when one resource depends on another. You must release the dependent resource first. The following example prints each step so you can see the order.
from contextlib import contextmanager
@contextmanager
def tracked(name):
print(f"enter {name}")
try:
yield name
finally:
print(f"exit {name}")
with tracked("A") as a, tracked("B") as b, tracked("C") as c:
print("body", a, b, c)The output is:
enter A
enter B
enter C
body A B C
exit C
exit B
exit AWhat happens when something fails
Suppose B raises an exception while it is being entered. A was already entered successfully, so Python calls A.__exit__ with the exception details. C is never entered, so it is never exited.
@contextmanager
def tracked(name, fail=False):
print(f"enter {name}")
if fail:
raise RuntimeError(f"{name} failed to start")
try:
yield name
finally:
print(f"exit {name}")
try:
with tracked("A") as a, tracked("B", fail=True) as b, tracked("C") as c:
print("body")
except RuntimeError as e:
print("caught:", e)The output is:
enter A
enter B
exit A
caught: RuntimeError: B failed to startThe last line differs slightly in practice: e prints as B failed to start, so the program prints caught: B failed to start. The key point is that A is cleaned up and C is untouched.
An exception in the body works the same way. Each manager's __exit__ receives the exception, starting with the rightmost one. If a manager suppresses the exception by returning True, the managers to its left see no exception at all.
from contextlib import suppress
with open("log.txt", "w") as log, suppress(ValueError):
log.write("start\n")
int("not a number")
log.write("never written\n")
print("done")Here suppress is exited first and swallows the ValueError. The file log is then closed normally, and the program prints done.
Parentheses for long statements
A with line with several managers can get long. A backslash continuation works but is fragile. Since Python 3.10, you can wrap the managers in parentheses and put one per line:
with (
open("in.txt") as src,
open("out.txt", "w") as dst,
):
dst.write(src.read())A trailing comma is allowed. This form is officially part of the grammar from Python 3.10 (it also happened to work in 3.9).
Common mistakes
- Using one
asname twice. The second assignment overwrites the first, and you lose access to the first resource. - Assuming all managers are entered before any code runs. Each manager is entered only after the one to its left succeeds.
- Hiding a failure with
suppresson the left. A manager listed earlier is exited later, so it never sees an exception that a manager to its right suppressed.
When the number of managers is not known until run time, the comma form does not help. The ExitStack chapter covers that case.
Exercise
In with tracked("X") as x, tracked("Y") as y, tracked("Z") as z:, tracked("Z") raises an exception in __enter__. Which managers have their __exit__ called, and in what order?
Show answer
Y is exited first, then X. Z was never successfully entered, so its __exit__ is not called. X and Y were entered, so they are cleaned up in reverse order of entry.
Exercise
Rewrite the following nested code as a single parenthesized with statement: with open("a.txt") as a: followed by an indented with open("b.txt", "w") as b: and the body b.write(a.read()).
Show answer
with ( open("a.txt") as a, open("b.txt", "w") as b, ): b.write(a.read())