Lesson 32 of 55
PythonContext Managers
20 minutes
Course progress58%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 32 of 55
Python20 minutes
Keep these ideas in mind as you work through the lesson.
The with statement simplifies resource management by ensuring setup and teardown happen automatically. A context manager implements __enter__ and __exit__.
# Built‑in file context manager (again)
with open('data.txt', 'r') as f:
data = f.read()
# Custom context manager using a class
class Timer:
def __enter__(self):
import time
self.start = time.time()
return self
def __exit__(self, exc_type, exc, tb):
import time
print('Elapsed:', time.time() - self.start)
with Timer() as t:
total = sum(i*i for i in range(1000000))
When the block ends, Timer.__exit__ runs automatically.