Sub topic 2
The with statement and the as clause
This chapter assumes you can write try/except/finally, define classes with methods, and read and write files with open(). You don't need to write your own context manager yet. That comes in later chapters. Here you will learn exactly what a with statement does, what the as name holds, and what happens to that name after the block ends.
The shape of the statement
A with statement has an expression, an optional as target, and an indented body.
with open("notes.txt", "w") as f:
f.write("first line\n")
f.write("second line\n")
print(f.closed)Running this prints True. The file was closed when the body finished, and f is still a valid name that refers to the closed file object.
The statement follows this order:
- Python evaluates the expression after
withonce. The result is the context manager, the object that controls setup and cleanup. - Python calls the manager's setup step. The value it returns is bound to the
astarget, if there is one. - Python runs the body.
- Python calls the manager's cleanup step, whether the body finished normally or not.
The setup and cleanup steps are the methods __enter__ and __exit__. The next chapter covers them in detail. For now, treat them as "setup" and "cleanup".
What the with statement replaces
Without with, a safe file write looks like this.
f = open("notes.txt", "w")
try:
f.write("first line\n")
finally:
f.close()The with form gives the same guarantee. The cleanup call is always paired with the setup call, and you cannot forget it. The manager's author writes the cleanup once, and every user gets it by writing with.
The pairing matters most when the body is long or has several exit points. You can write return, break, continue, or raise an exception from inside the body, and cleanup still runs.
import io
def first_line(text):
with io.StringIO(text) as buf:
line = buf.readline()
return line, buf # the return happens inside the block
line, buf = first_line("alpha\nbeta\n")
print(line.strip(), buf.closed)This prints alpha True. The function returned from inside the with block, yet buf was closed before the caller received it. The return value was computed first, then cleanup ran, then the function actually returned.
The as clause is optional
Many managers are used only for their side effects, so they need no name.
import threading
lock = threading.Lock()
counter = 0
def increment():
global counter
with lock:
counter += 1
threads = [threading.Thread(target=increment) for _ in range(10)]
for t in threads:
t.start()
for t in threads:
t.join()
print(counter)This prints 10. The lock is acquired on entry and released on exit. The body never needs to refer to a value from the manager, so there is no as.
Use as only when the body needs something the manager hands out, such as a file object, a connection, or a path.
What as actually binds
This is the point intermediate learners most often get wrong. The name after as is bound to the return value of the setup step. It is not bound to the context manager itself.
For most file-like objects, setup returns the object itself, so the two are the same thing. That is why with open(...) as f seems to bind the manager. The following class returns something else, which shows the difference.
class Announce:
def __init__(self, label):
self.label = label
def __enter__(self):
print(f"enter {self.label}")
return self.label.upper()
def __exit__(self, exc_type, exc_value, traceback):
print(f"exit {self.label}")
return False
with Announce("db") as name:
print("body sees", name)
print("after the block, name is still", name)The output is:
enter db
body sees DB
exit db
after the block, name is still DBname is the string "DB", not an Announce object. If you needed the manager, you would have to keep your own reference:
manager = Announce("db")
with manager as name:
pass
print(manager.label, name)The standard library has many managers whose as value differs from the manager.
| Expression | What `as` receives |
|---|---|
| `open("a.txt")` | The file object itself |
| `threading.Lock()` | `True`, the result of acquiring the lock |
| `tempfile.TemporaryDirectory()` | The directory path as a string |
| `decimal.localcontext()` | A copy of the current decimal context, which you can modify |
| `unittest.TestCase.assertRaises(...)` | A recorder object whose `exception` attribute holds the caught exception |
The lesson is to read the documentation for each manager. Never assume as gives you the object in the with line.
Any assignment target works
The as target follows the same rules as the left side of an assignment. It can be a plain name, a tuple pattern, an attribute, or a subscript. contextlib.nullcontext is useful for demonstrating this because it returns whatever value you pass it.
from contextlib import nullcontext
with nullcontext((1, 2)) as (a, b):
print(a, b)
class Holder:
pass
holder = Holder()
registry = {}
with nullcontext("hello") as holder.value:
pass
with nullcontext("world") as registry["key"]:
pass
print(holder.value, registry)This prints 1 2, then hello {'key': 'world'}. Tuple unpacking only works if the setup value really is a sequence of the right length. If it isn't, you get the same TypeError or ValueError as with ordinary unpacking, and you get it before the body runs.
Scope: the name outlives the block
A with statement does not create a new scope. This is the same rule as for if and for. The as name stays bound after the block, and it still refers to the same object.
For a file, that object is now closed, and using it fails.
with open("notes.txt", "w") as f:
f.write("data")
try:
f.write("more")
except ValueError as error:
print(error)This prints I/O operation on closed file. The cleanup released the resource, but nothing removed the name. The practical rule is to finish all work with the resource inside the block. If you need the data afterwards, copy it out. Read the contents into a variable and use that variable, not the file object.
with open("notes.txt") as f:
contents = f.read()
print(len(contents))Exceptions and the with statement
If the body raises an exception, cleanup runs first, then the exception continues upward as it would from any other code. A manager can choose to suppress the exception, but most do not. Later chapters cover how.
try:
with open("notes.txt") as f:
raise RuntimeError("something went wrong in the body")
except RuntimeError as error:
print("caught:", error, "| closed:", f.closed)This prints caught: something went wrong in the body | closed: True. The file was closed before the except clause ran.
Exceptions raised by the expression itself, such as open("missing.txt") raising FileNotFoundError, happen before any manager exists. No cleanup runs, because nothing has been acquired. A with statement does not catch such errors, so wrap the whole statement in try/except if you want to handle them.
try:
with open("does-not-exist.txt") as f:
data = f.read()
except FileNotFoundError:
data = ""
print(repr(data))Several managers on one line
You can list more than one manager, separated by commas. They are entered left to right and exited in the opposite order.
with open("in.txt", "w") as src:
src.write("copy me")
with open("in.txt") as src, open("out.txt", "w") as dst:
dst.write(src.read())Python 3.10 and later also allow parentheses around the list, which lets you split a long statement over several lines.
with (
open("in.txt") as src,
open("out.txt", "w") as dst,
):
dst.write(src.read())Each later expression can use names bound earlier in the same statement. This is equivalent to nesting one with inside another. A later chapter covers composition and ExitStack.
Common errors
- Expecting
asto give the manager. Check what the setup step returns. Withsqlite3.connect(),asgives the connection, but leaving the block commits or rolls back the transaction and does not close the connection.
import sqlite3
conn = sqlite3.connect(":memory:")
with conn as c:
c.execute("create table t (x)")
print(c is conn)
print(conn.execute("select 1").fetchone()) # still open
conn.close()This prints True and then (1,). A connection that is still usable after the block shows why you must check what a given manager's cleanup actually does. Do not assume it matches what open() does.
- Using the resource after the block. The name still exists, but the resource is released. Read or process everything inside the block.
- Putting the acquisition outside the statement. In
f = open(path)followed bywith f:, the file opens even if something fails between the two lines. Preferwith open(path) as f:so acquisition and cleanup are paired. - Assuming
withcatches errors. It guarantees cleanup. It does not handle exceptions unless the manager is designed to suppress them. - Reusing a manager object. Some managers can only be used once. A closed file cannot be entered again. The reuse chapter covers this.
Summary of the rules
- The expression after
withis evaluated once, and its result is the manager. - The
astarget receives the value returned by the manager's setup step, which may or may not be the manager. - The target can be any assignment target, and it stays bound after the block.
- Cleanup runs on normal completion, on
return,breakandcontinue, and on exceptions. - Exceptions from the body propagate after cleanup unless the manager suppresses them.
- Exceptions from evaluating the expression happen before any cleanup is registered.
Exercise
What does this code print, and in what order do the lines appear? Use the Announce class from earlier in this chapter.
for i in range(3):
with Announce(f"loop {i}"):
if i == 1:
continue
print("body", i)
Show answer
It prints "enter loop 0", "body 0", "exit loop 0", then "enter loop 1", "exit loop 1", then "enter loop 2", "body 2", "exit loop 2". The continue skips the print call but not cleanup, so "exit loop 1" still appears.
Exercise
A colleague writes with open("data.txt") as f: pass and then, on the next line outside the block, calls f.read(). What happens, and what is the fix?
Show answer
The call raises ValueError: I/O operation on closed file. The with block closed the file when it ended, although the name f is still bound. The fix is to call f.read() inside the block and store the result in a variable, for example contents = f.read(), and use that variable afterwards.
Exercise
Why does with sqlite3.connect(":memory:") as conn: not guarantee that the connection is closed afterwards, and how can you check what a manager's as value and cleanup do?
Show answer
The cleanup of the sqlite3 connection manager commits or rolls back the current transaction. It does not call close(). The as value is the connection itself, so the object remains open and usable after the block. To check any manager, read its documentation and test it: print the as value's type and inspect its state, such as a closed attribute, after the block.