Skip to content

Context Managers and the with Statement

The with statement guarantees that setup and teardown code runs, even if an exception occurs in The block body. It is the primary mechanism for resource management in Python.

## Basic form
with open("data.txt") as f:
content = f.read()
## Equivalent to:
f = open("data.txt")
try:
content = f.read()
finally:
f.close()
# Sequential — both opened, both closed
with open("input.txt") as infile, open("output.txt", "w") as outfile:
outfile.write(infile.read())
# Nested — same as above, different syntax
with open("input.txt") as infile:
with open("output.txt", "w") as outfile:
outfile.write(infile.read())
# Parenthesized form (Python 3.10+)
with (
open("input.txt") as infile,
open("output.txt", "w") as outfile,
):
outfile.write(infile.read())
## Cross-References
  • Advanced Typing: Extends Python’s type system with protocols and generics, which can be used to type context managers more precisely.
  • Data Validation: Shows how to validate data within context managers, ensuring resources receive properly validated input.
  • Protocols and Dunder Methods: Explains the enter and exit dunder methods that define context manager protocol.
  • Async Context Managers: Builds on context managers for asynchronous resource management with async with and async generators.