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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Context Managers | Python Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. Python Fundamentals

Lesson 32 of 55

·Python

Context Managers

20 minutes

Course progress58%

What you'll learn

Keep these ideas in mind as you work through the lesson.

3 points
  • `with` ensures `__exit__` runs even if an error occurs.
  • Commonly used for files, sockets, locks, and timers.
  • Can be created with a class or via `contextlib.contextmanager`.

Context Managers

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.

Make it stickPractice what you've learned1 quiz · 5 practical tests · Optional activities from Python FundamentalsBrowse activities
Previous lessonGenerators and IteratorsContinue to lesson 33Unit Testing with unittestBack to Python Fundamentals curriculum