Lesson 32 of 55 · Python
Context Managers
Duration: 20 minutes
Lesson 32 of 55 · Python
Duration: 20 minutes
with statement simplifies resource management by ensuring setup and teardown happen automatically. A context manager implements __enter__ and __exit__.\n\npython\n# Built‑in file context manager (again)\nwith open('data.txt', 'r') as f:\n data = f.read()\n\n# Custom context manager using a class\nclass Timer:\n def __enter__(self):\n import time\n self.start = time.time()\n return self\n def __exit__(self, exc_type, exc, tb):\n import time\n print('Elapsed:', time.time() - self.start)\n\nwith Timer() as t:\n total = sum(i*i for i in range(1000000))\n\n\nWhen the block ends, Timer.__exit__ runs automatically.\n