Ctrl K
Python · Mid-level · Theory

You 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?

~4 min by voice

How to approach it

The interviewer wants to see whether you understand the context manager protocol at the level of mechanics: when and with what arguments __exit__ is called, how exception suppression works, and why the generator version via contextmanager doesn't release the resource on an error without try/finally.

Have you seen this question in a real interview?
Answers0
Avg. score—
Strong—
Practiced0
Topics
Similar questionsWhat is a context manager, and how does the with statement work? How do you write your own context manager? JuniorHow 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? Senior

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