Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. Python Fundamentals

Lesson 32 of 55 · Python

Context Managers

Duration: 20 minutes

Context Managers\n\nThe 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

Previous: Generators and IteratorsNext: Unit Testing with unittest