A context manager controls setup and cleanup around a block of code.
The with statement is the common way to use context managers, especially for files, locks, database connections, and temporary resources.
Good context manager code makes cleanup reliable even when an error happens inside the block.
with opens a controlled block and guarantees that the context manager can clean up after the block ends.
from pathlib import Path
path = Path("notes.txt")
path.write_text("Python context managers", encoding="utf-8")
with path.open("r", encoding="utf-8") as file:
text = file.read()
print(text)
Python context managers
The file is closed automatically when the with block ends.
A class can become a context manager by defining __enter__ and __exit__ methods.
from time import perf_counter
class Timer:
def __enter__(self):
self.start = perf_counter()
return self
def __exit__(self, exc_type, exc, traceback):
self.elapsed = perf_counter() - self.start
with Timer() as timer:
total = sum(range(1000))
print(total)
print(timer.elapsed >= 0)
499500
True
Timer records setup in __enter__ and cleanup work in __exit__.
contextlib.contextmanager lets a generator function behave like a context manager.
Context managers are best when forgetting cleanup would leak a file, connection, lock, timer, or temporary state.
Try this next
0 of 3 completed
with makes cleanup automatic, including when an exception happens inside the block.
Returning true suppresses the exception. Most beginner context managers should return false or nothing.
Files, database connections, locks, temporary directories, timers, and test fixtures commonly use context managers.
Explore 500+ free tutorials across 20+ languages and frameworks.