Python Tutorial 0/52 lessons ~6 min read Lesson 36
Context Managers
Context managers (the with protocol) guarantee setup/teardown.
Course progress0%
Focus
8 guided sections
Practice signal
Examples included
Career prep
Foundation builder
Introduction
Context managers (the with protocol) guarantee setup/teardown. Implement via __enter__/__exit__ or the @contextmanager decorator.
Understanding the topic
Core concepts to understand:
withcalls__enter__/__exit__.@contextmanagerturns a generator into one.- Used for files, locks, DB sessions, timers.
__exit__can suppress exceptions.
Syntax reference
Visual flow / code:
python
from contextlib import contextmanagerimport time@contextmanagerdef timer(label: str):start = time.perf_counter()try:yieldfinally:print(f"{label}: {time.perf_counter()-start:.3f}s")with timer("db query"):run_query()# Class-basedclass Connection:def __enter__(self):self.conn = connect()return self.conndef __exit__(self, *exc):self.conn.close()with Connection() as conn:conn.execute(...)
Execution workflow
1Context Managers Workflow
1 / 4Step 1
with calls __enter__ / __exit__.
Apply this step while implementing context managers in real code.
Real-world use
Database sessions, file locks, distributed transactions — all use context managers to guarantee cleanup. Critical for resource safety.
Best practices
- Prefer @contextmanager for simple cases.
- Always release resources in
__exit__. - Use
ExitStackfor dynamic stacks.
Hands-on exercise
Interview preparation — practice these questions:
- Walk through __enter__/__exit__.
- @contextmanager — how does it work?
- What does ExitStack do?
Summary
In summary: with = guaranteed cleanup. @contextmanager is the easy way.
Ready to mark this lesson complete?Track your journey across the entire course.