Ctrl K
Python · Senior · Theory

How does a context manager work under the hood? What happens to an exception inside a with block, and how would you write a manager that handles a database transaction?

~4 min by voice

How to approach it

This checks whether you understand the context manager protocol: how with calls __enter__ and __exit__, and how an exception passes through __exit__ and gets suppressed. Second, whether you can apply it to a real task: a transaction with commit and rollback, nesting and async.

Have you seen this question in a real interview?
Answers0
Avg. score—
Strong—
Practiced0
Topics
Similar questionsYou need to guarantee that a resource, say a lock or a temporary directory, gets released even if the code inside fails with an exception. How would you implement your own context manager, and how do the different ways of doing it differ? Mid-levelWhat is a context manager, and how does the with statement work? How do you write your own context manager? JuniorWhich data structures from the collections module do you know, and what are they for? JuniorWhen do you use functools.lru_cache, and what problems can you run into with it? Mid-level

Answer by voice

The interviewer will ask this question and listen. Think out loud and ask for a hint if you need one. When you're done, pause or tap “That's my answer”. In about a minute, your score and the points you covered show up here.

Sign in to answer

Best with headphones · ~4 min