Skip to content

Context Managers and the with Statement

import Citations from ‘@components/Citations.astro’

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())

Context managers are Python’s way of ensuring cleanup happens. The with statement guarantees that resources are released when the block exits, even if an exception occurs. Think of a context manager as a hotel check-in/check-out: you get the room (resource acquisition) on entry and return the key (cleanup) on exit. The @contextmanager decorator lets you write context managers as generators, making them easy to create for custom resources like database connections or temporary files.

<Citations sources={[ {title=“Fluent Python”, author=“Ramalho”, year=“2022”, type=“book”}, {title=“Python Cookbook”, author=“Beazley and Jones”, year=“2013”, type=“book”}, ]} />