Sub topic 2
The with statement and the as clause
This chapter assumes you know Python functions, classes, and methods, how try/except/finally works, and how to use open() to read and write files. The previous chapter showed why cleanup needs a guarantee. This chapter shows how the with statement provides that guarantee and what the as clause binds.
The shape of a with statement
A with statement runs a block of code between a setup step and a cleanup step. The object that defines those steps is called a context manager.
with open("data.txt", "w") as f:
f.write("hello")This does three things in order:
- Python evaluates the expression after
with, hereopen("data.txt", "w"). The result is the context manager. - Python runs the manager's setup step. For a file, the file is already open at this point.
- Python runs the indented block. When the block ends for any reason, Python runs the manager's cleanup step. For a file, that step calls
close().
The cleanup runs after a normal finish, after an exception, and after return, break, or continue inside the block. This is the same guarantee as try/finally, with less code.
# Manual cleanup
f = open("data.txt", "w")
try:
f.write("hello")
finally:
f.close()
# Same guarantee with with
with open("data.txt", "w") as f:
f.write("hello")The with version removes the chance of forgetting close(). It also keeps the opening of the resource and its cleanup in one place.
What the as clause binds
The as clause is optional. When present, the name after as is bound to the value returned by the setup step. That value is not always the context manager itself.
with open("data.txt") as f:
print(f is open) # False: f is a file objectFor files, the setup step returns the file object, so f and the manager are the same object. Other managers return something different. A database connection manager might return a cursor. A directory-changing manager might return the new path. The documentation of each manager tells you what as receives.
If you do not need the value, leave out as:
import threading
lock = threading.Lock()
with lock:
print("holding the lock")Here the lock is acquired on entry and released on exit. Nothing is bound, because nothing needs to be.
The name outlives the block
A with block does not create a new scope. The name bound by as stays available after the block ends, and so does every variable assigned inside it.
with open("data.txt") as f:
first_line = f.readline()
print(first_line) # works
print(f.closed) # True: the file is closed, but f still existsThe cleanup has happened, but the name still refers to the object. Using a closed file raises ValueError, so read what you need inside the block.
Unpacking in the as clause
The target after as follows the same rules as an assignment target. You can unpack a returned tuple:
from contextlib import nullcontext
with nullcontext((1, 2)) as (x, y):
print(x, y) # 1 2nullcontext returns the value you give it, so this shows the unpacking without any real resource. It appears again in a later chapter on contextlib helpers.
A flow to keep in mind
The setup and cleanup steps are methods named __enter__ and __exit__. The next chapter covers them in detail, including how __exit__ can see and suppress an exception.
Common errors
- Using the resource after the block. The name still exists, but the resource is closed or released. Finish your work inside the block.
- Expecting
asto give the manager. If a manager returns something else from setup, the name holds that value. Check the documentation. - Expecting a failed setup to run cleanup. If the expression or the setup step itself raises, the block never starts and cleanup does not run, because nothing was acquired.
Exercise
In the code below, what is printed, and why does the last line fail? with open("data.txt", "w") as f: f.write("hello") print(f.closed) f.write("again")
Show answer
It prints True, because the with block closed the file on exit. The name f still refers to the file object, but f.write("again") raises ValueError: I/O operation on closed file, since the file was closed when the block ended.
Exercise
Does a with block create a new variable scope? What does this mean for a variable assigned inside the block?
Show answer
No. A with block shares the scope of the code around it. A variable assigned inside the block, and the name bound by as, remain available after the block ends.