Intermediatehow it works Verified ~8 min
What does the Python with statement do, and how do you write a context manager for a database transaction?
Source: Python tutorial: data structures
Quick answerFree
with calls __enter__ before the block and __exit__ after it, even if the block raises, so clean-up always runs. A transaction context manager opens a cursor, commits when the block succeeds, rolls back and re-raises on an exception, and always closes the cursor. Write it with @contextlib.contextmanager or a class.
Detailed answer· ~190 words
Interview PrepUnlock the full answer with Interview Prep
Get a ~190-word model answer, 5 key points, a visual explainer, 5 common mistakes and 5 follow-ups, plus 233 more Python questions.
Also in Pro (₹499 / 90 days).
Key points· 5 points
Interview PrepUnlock with Interview Prep
Visual explainer· animated, step by step
Interview PrepUnlock with Interview Prep
Common mistakes· 5
Interview PrepLocked
Best practices· 4
Interview PrepLocked
Likely follow-ups· 5 questions
Interview PrepUnlock with Interview Prep
+ 233 more Python questions in Interview Prep, each with the full answer.