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
Interview Q&A included
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 / 4with calls __enter__ / __exit__
with calls __enter__ / __exit__.
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.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1IntermediateQuestionWalk through __enter__/__exit__.+
Answer
On
with obj as x:, Python calls obj.__enter__() and binds its return value to x. When the block ends, normally or by exception, it calls obj.__exit__(exc_type, exc, tb). If __exit__ returns a true value the exception is suppressed; otherwise it propagates. This is how files, locks, and transactions get reliable cleanup.Follow-up
What is the async equivalent?
2IntermediateQuestion@contextmanager — how does it work?+
Answer
contextlib.contextmanager turns a generator function with a single yield into a context manager. Code before the yield acts as __enter__, the yielded value is bound by as, and code after it acts as __exit__. Exceptions from the block are thrown into the generator at the yield, so wrap it in try/finally to guarantee cleanup.Follow-up
What happens if you forget the
try/finally?3AdvancedQuestionWhat does ExitStack do?+
Answer
contextlib.ExitStack manages a dynamic number of context managers and cleanup callbacks. You register them with enter_context() or callback(), and on exit they are unwound in last-in, first-out order, with exceptions handled as in nested with blocks. It is useful when the number of resources is only known at runtime, or for optional resources.Follow-up
How does
pop_all() help with transferring ownership of resources?Summary
In summary: with = guaranteed cleanup. @contextmanager is the easy way.
Ready to mark this lesson complete?Track your journey across the entire course.