Context Managers (with)
The problem
Files, network connections and locks must be closed or released, even when an error happens halfway through.
The solution: with
with open("data.txt", "w") as f:
f.write("Hello")
# the file is closed here, even if write() failed
with calls __enter__ at the start and __exit__ at the end, no matter what.
Writing your own
Option 1: a class with __enter__ and __exit__.
Option 2 (easier): @contextmanager with yield:
from contextlib import contextmanager
@contextmanager
def timer():
start = time.perf_counter()
yield # the with-block runs here
print(time.perf_counter() - start)
Put cleanup in try/finally around the yield so it also runs when the block raises.
Handy built-ins
contextlib.suppress(FileNotFoundError)silently ignores one specific error.open(),sqlite3.connect()andthreading.Lock()all work withwith.
▶️ Runs in the app (files live in the app's temporary memory).
Example
from contextlib import contextmanager, suppress
import os
import time
with open("data.txt", "w") as f:
f.write("Hello file!")
print(f.closed) # True — closed automatically
@contextmanager
def timer(label):
start = time.perf_counter()
try:
yield
finally:
print(f"{label}: {time.perf_counter() - start:.4f}s")
with timer("sum"):
total = sum(range(1_000_000))
with suppress(FileNotFoundError):
os.remove("missing.txt") # no crash
print("still running")