Context managers and with
More Python9 min readLesson 4 of 7
4.1 Cleanup that cannot be skipped
Opening a file takes a resource that must be released even if the body raises. The with statement guarantees that. The object it receives implements two methods: __enter__ runs on entry, and __exit__ runs on the way out, including on exceptions.
The standard library uses this pattern for files, locks, database transactions and temporary directories. Use it whenever an operation pairs setup with cleanup.
with open("notes.txt", "w", encoding="utf-8") as handle:
handle.write("First line\n")
with open("notes.txt", encoding="utf-8") as handle:
print(handle.read().strip())Output
First line
To build your own, either write a class with __enter__ and __exit__, or decorate a generator with contextlib.contextmanager. The generator form yields once; the code after the yield is the cleanup.
from contextlib import contextmanager
@contextmanager
def heading(text):
print("==", text, "==")
yield
print("-- end --")
with heading("Result"):
print("42")Output
== Result == 42 -- end --
