`with`
with runs a block of code while a resource is checked out, and guarantees the matching cleanup step runs when the block ends — whether it ends normally, by a return, or by an exception.
Detailed Explanation
Before with, every piece of code that acquired something had to release it by hand. You opened a file, did the work, and called close(). That works until the work in the middle raises. Then close() never runs, the file descriptor leaks, and buffered writes are lost. The correct pre-with pattern was try / finally, which is four extra lines around every resource and easy to forget.
with is that try / finally pattern turned into one statement. with open("access.log") as log: acquires the file, binds it to log, runs your block, and releases the file on the way out. There is no path out of the block that skips the release. An exception, a return, a break, even a continue that jumps to the next loop iteration — all of them run the cleanup first.
The expression after with must be a context manager: an object that knows how to set itself up and tear itself down. Files, locks, database connections, and sockets are all context managers out of the box. The mechanics of how an object qualifies belong to the context managers entry, cross-referenced below. For the statement itself you need two facts.
First, the name after as is not the context manager. It is whatever the manager's setup step hands back. For a file those happen to be the same object, so with open(path) as f gives you the file. For sqlite3 they are not: with connection: manages the transaction, committing on success and rolling back on an exception, and does not close the connection. Read the documentation for each manager rather than assuming that with means "close this".
Second, as is optional. with balance_lock: is complete and idiomatic, because a lock has nothing useful to hand you. You want the block guarded, not a value.
You can manage several resources in one statement by separating them with commas. with open(src) as source, open(dst, "w") as sink: is exactly equivalent to nesting two with statements. The managers are entered left to right and exited right to left, so if opening dst fails, source is still closed correctly. Since Python 3.10 you may wrap that list in parentheses and break it across lines, which is the readable choice once you have three or more managers.
When the number of resources is only known at runtime — you are opening one output file per shard, and the shard count comes from a config file — a comma list cannot express that. Use contextlib.ExitStack, which lets you push managers on in a loop and unwinds all of them at the end.
Three limits are worth knowing. with does not create a new scope, so names bound inside it, including the as name, outlive the block; the object is merely torn down. with does not by itself swallow exceptions — a manager must explicitly opt into that, and most do not. And the async variant is a different statement: coroutines that hold resources need async with, not with.
Code Examples
from pathlib import Path
# Setup: a small log file to read back.
Path("access.log").write_text("200 /home\n500 /checkout\n200 /home\n")
# The file is closed when the block ends, even if the body raises.
with open("access.log", encoding="utf-8") as log:
error_lines = [line for line in log if line.startswith("5")]
print(error_lines) # ['500 /checkout\n']
print(log.closed) # True <- cleanup already ran
# `with` is not a scope: `log` still exists here, it is only closed.
try:
log.read()
except ValueError as exc:
print(exc) # I/O operation on closed file.# What `with` expands to. These two functions behave identically.
from threading import Lock
balance_lock = Lock()
balance = 0
def deposit_with(amount):
global balance # we are rebinding a module-level name
with balance_lock: # no `as`: we want the guard, not a value
balance += amount
def deposit_manual(amount):
global balance
balance_lock.acquire() # the pre-`with` spelling
try:
balance += amount
finally:
balance_lock.release() # must run even if the body raises
deposit_with(50)
deposit_manual(25)
print(balance) # 75from contextlib import ExitStack
from pathlib import Path
Path("raw.csv").write_text("id,City\n1,Pune\n2,Kochi\n")
# Several managers in one statement, entered left to right.
with (
open("raw.csv", encoding="utf-8") as source, # parenthesized form: Python 3.10+
open("clean.csv", "w", encoding="utf-8") as sink,
):
for line in source:
sink.write(line.lower())
print(Path("clean.csv").read_text().splitlines()) # ['id,city', '1,pune', '2,kochi']
# ExitStack when the number of resources is only known at runtime.
shard_names = ["shard-0.txt", "shard-1.txt", "shard-2.txt"]
with ExitStack() as stack:
shards = [stack.enter_context(open(name, "w")) for name in shard_names]
for index, shard in enumerate(shards):
shard.write(f"shard {index}\n")
# All three files are closed here, in reverse order of opening.
print(Path("shard-1.txt").read_text()) # shard 1Common Gotchas
`with` is not a scope
the `as` name survives the block, but the object behind it has been torn down. Reading from a file after its `with` block raises `ValueError: I/O operation on closed file`. Do the work inside the block, or copy out the data you need before it ends.
The `as` name is not always "the thing to close"
for `sqlite3`, `with conn:` commits or rolls back a transaction and leaves the connection open. Wrapping it in `with` and assuming the connection is gone afterwards leaks connections under load.
Cleanup only covers managers already entered
in `with open(src) as source, open(dst, "w") as sink:`, if `open(src)` itself raises, nothing is released because nothing was acquired. Failures *inside* the body are always covered; a failure while acquiring the first manager is not.
Parenthesized managers need Python 3.10+
on Python 3.9 and earlier, `with (open(a) as f, open(b) as g):` is a syntax error, and `with (cm_one, cm_two):` is parsed as a *tuple*, which is not a context manager and fails at runtime. Use a plain comma list if you must support older interpreters.