Context managers ensure resources are properly acquired and released. The most common is with open("file.txt") as f: — the file auto-closes even if an exception occurs.
The __enter__ and __exit__ methods define context behavior. contextlib provides utilities: @contextmanager decorator, suppress(), and ExitStack.
Practical uses: database connections, file locks, temporary directories, network connections, and profiling timers.
Context managers prevent resource leaks, which are dangerous in long-running applications. They are more reliable than manual cleanup in try/finally blocks.
Create custom context managers with @contextmanager decorator: setup code before yield, cleanup code after.