What Are Context Managers in Python?
A context manager defines setup and teardown behavior for a block of code using the "with" statement, guaranteeing cleanup happens even if an error occurs in...
Published November 21, 2026
A context manager sets something up before a block and guarantees cleanup afterwards, even if an error occurs. You use it with the with statement, such as with open('f.txt') as f.
The concept
It works through two methods: __enter__ runs at the start (and returns the resource) and __exit__ runs at the end, receiving any exception.
The contextlib module lets you write them as simple generator functions with @contextmanager.
Lifecycle
- with starts: __enter__ is called
- The block runs using the resource
- The block ends or raises
- __exit__ always runs and cleans up
Practical examples
Files
with open('data.txt', encoding='utf-8') as f:
text = f.read() # file is closed automaticallyCustom class
class Timer:
def __enter__(self):
import time; self.t = time.perf_counter(); return self
def __exit__(self, *exc):
import time; print(time.perf_counter() - self.t)
with Timer(): sum(range(10**6))@contextmanager
from contextlib import contextmanager
@contextmanager
def cd(path):
import os; old = os.getcwd(); os.chdir(path)
try: yield
finally: os.chdir(old)Locks
with lock:
shared += 1Common mistakes
- Forgetting finally in @contextmanager generators.
- Swallowing exceptions by returning True from __exit__ accidentally.
- Not using with for files, locks and connections.
Key takeaways
- with = setup + guaranteed cleanup.
- __enter__ and __exit__.
- @contextmanager makes them easy.
FAQ
Multiple managers?
with open(a) as f, open(b) as g: works.
Async version?
async with uses __aenter__ and __aexit__.