Sub topic 8
Several context managers in one with statement
This chapter assumes you can write a single with block, know what __enter__ and __exit__ do, and understand how __exit__ can suppress an exception. It covers how to combine several managers in one statement, in what order they run, and what happens when one of them fails.
Why combine managers
Real code often needs more than one resource at once. Copying a file needs a source and a destination. A database job might need a connection, a transaction, and a lock. You could nest with blocks, but each level adds indentation, and the code drifts to the right.
with open("input.txt") as source:
with open("output.txt", "w") as target:
target.write(source.read())Python lets you list the managers in one statement, separated by commas:
with open("input.txt") as source, open("output.txt", "w") as target:
target.write(source.read())The two forms mean the same thing. The comma form is not a different feature. It is shorthand for nesting, with the first manager as the outermost block.
The equivalence with nesting
A statement of the form
with A() as a, B() as b:
bodybehaves exactly like
with A() as a:
with B() as b:
bodyThis equivalence explains every rule in the rest of the chapter. Each manager gets its own complete enter, body, and exit cycle. The cycle for B sits inside the cycle for A.
Order of entering and exiting
Managers are entered left to right and exited right to left. The last manager entered is the first one exited, as with a stack. This order matters because later resources often depend on earlier ones. A transaction must finish before its connection closes, so the connection must be listed first.
To see the order, use a small manager that reports what it does. The later snippets in this chapter reuse this Tracer class.
class Tracer:
def __init__(self, name, fail_on_enter=False):
self.name = name
self.fail_on_enter = fail_on_enter
def __enter__(self):
print(f"enter {self.name}")
if self.fail_on_enter:
raise RuntimeError(f"{self.name} failed to enter")
return self
def __exit__(self, exc_type, exc_value, traceback):
kind = exc_type.__name__ if exc_type else None
print(f"exit {self.name} ({kind})")
return False
with Tracer("a") as a, Tracer("b") as b:
print("body")The output is:
enter a
enter b
body
exit b (None)
exit a (None)Expressions are evaluated one at a time
Because the statement is shorthand for nesting, the expression for each manager is evaluated only after the previous manager has been entered. This has two consequences.
First, a later expression can use the name bound by an earlier as clause:
from pathlib import Path
Path("config.txt").write_text("name=demo\n")
with open("config.txt") as config, open(config.name + ".bak", "w") as backup:
backup.write(config.read())Here config.name is the file name, so the second open() call can only run once the first file is open.
Second, if creating a later manager fails, the earlier managers are still cleaned up. They were already entered, so they will be exited.
When a later manager fails to enter
Suppose the second of three managers raises an exception in __enter__:
try:
with Tracer("a"), Tracer("b", fail_on_enter=True), Tracer("c"):
print("body")
except RuntimeError as error:
print("caught:", error)The output is:
enter a
enter b
exit a (RuntimeError)
caught: b failed to enterThree things happen here:
awas entered successfully, so its__exit__runs. It receives theRuntimeErrorlike any other exception from inside its block.bnever finished entering, so its__exit__is not called. A manager that fails in__enter__must clean up after itself before raising.cis never created, because its expression is never evaluated. The body does not run.
This is the main reason to list managers in one statement instead of building them beforehand. If you create the objects first, they exist even when an earlier one fails to enter, and objects like open files may never be closed.
# Risky: the second open() may fail after the first file is already open
source = open("input.txt")
target = open("/no/such/dir/output.txt", "w")
with source, target:
...If the second open() raises, source is never closed, because no with statement has started. Write with open(...) as source, open(...) as target: so that each file is opened only inside the statement.
How exceptions pass through several managers
An exception raised in the body goes to the innermost manager first, which is the rightmost one. If its __exit__ returns a false value, the exception continues to the next manager outward. If it returns a true value, the exception stops there, and the outer managers see a normal exit.
The position of a suppressing manager therefore decides what the other managers see. Compare these two statements, using contextlib.suppress:
from contextlib import suppress
with Tracer("outer"), suppress(KeyError):
{}["x"]
print("after first")
with suppress(KeyError), Tracer("inner"):
{}["x"]
print("after second")The output is:
enter outer
exit outer (None)
after first
enter inner
exit inner (KeyError)
after secondIn the first statement, suppress is innermost. It swallows the KeyError before outer can see it, so outer exits normally. In the second statement, Tracer is innermost and sees the error. suppress then swallows it. Both statements continue after the block, but the tracer saw different things.
| Order of managers | What the other manager's `__exit__` receives |
|---|---|
| Tracer first, `suppress` second | `None`, because the error is already handled |
| `suppress` first, Tracer second | The `KeyError` |
A manager that commits on success and rolls back on failure must be positioned so that it sees the exception. If a suppressing manager sits inside it, the transaction commits even though the body failed.
Errors raised while exiting
Each __exit__ runs in its own cycle, so a failure in one does not prevent the others. If the __exit__ of B raises an exception, the __exit__ of A still runs. It receives the new exception as its arguments. If the body had already raised an error, Python keeps it as the __context__ of the new one, and the traceback shows both. This is why cleanup code with several managers is safer than a hand-written sequence of close() calls. In a sequence of calls, one failure skips the rest.
Parenthesized form for long statements
Real statements get long. Before Python 3.10 the only way to break them across lines was a backslash:
with open("a.txt") as a, \
open("b.txt") as b, \
open("c.txt", "w") as c:
c.write(a.read() + b.read())Python 3.10 officially supports parentheses around the list of managers, which allows a trailing comma and one manager per line:
from pathlib import Path
Path("a.txt").write_text("A\n")
Path("b.txt").write_text("B\n")
with (
open("a.txt") as a,
open("b.txt") as b,
open("c.txt", "w") as c,
):
c.write(a.read() + b.read())The meaning does not change. This is still the same nesting, entered top to bottom. Use the parenthesized form only if your code runs on Python 3.10 or later. On older versions, use backslashes, or nest the blocks.
Choosing between one statement and nesting
Prefer one statement when the managers are peers and nothing needs to happen between entering them. Prefer nesting in these cases:
- You need to run code between two entries, for example to validate the first resource before opening the second.
- Different managers need different
try/excepthandling around them. - A comment or a branch explains why the inner block exists, and it reads better as its own level.
Neither choice changes behavior. Pick the one that is easier to read.
When the number of managers is not fixed
A with statement lists its managers in the source code, so their number is fixed when you write it. If you need to open a list of files whose length is known only at run time, a fixed statement cannot express it. Python provides contextlib.ExitStack for that case, covered in a later chapter. It applies the same enter and exit ordering rules you learned here.
Common mistakes
- Creating managers ahead of the statement. Objects created earlier can leak if a later one fails. Create them inside the statement.
- Assuming a failed
__enter__triggers its own__exit__. It does not. Clean up inside__enter__before raising. - Putting a suppressing manager on the left by accident. The managers to its right still see the error, but the ones to its left do not.
- Assuming the right-hand manager is entered first. Entry is left to right. Only exit is reversed.
- Using parentheses on Python 3.9 or earlier. The syntax may fail or behave differently. Check your minimum supported version.
Exercise
What does this program print, and why? with Tracer("x"), Tracer("y", failonenter=True): print("body") Assume Tracer is the class from this chapter and the RuntimeError is not caught.
Show answer
It prints "enter x", then "enter y", then "exit x (RuntimeError)", and the program ends with an uncaught RuntimeError traceback. The manager y raised while entering, so its _exit is never called. The manager x was already entered, so its exit_ runs and receives the RuntimeError. The body never runs, so "body" is not printed.
Exercise
A transaction manager commits when its block exits normally and rolls back when it receives an exception. You write with suppress(ValueError), transaction(): and the body raises ValueError. Does the transaction commit or roll back? How would you change the statement to get the other behavior?
Show answer
It rolls back. transaction() is the rightmost manager, so it is innermost. It receives the ValueError first and rolls back, and then suppress swallows the error. If you wrote with transaction(), suppress(ValueError):, suppress would be innermost and would swallow the error before the transaction saw it. The transaction would then see a normal exit and commit.