Ctrl K
Python · Junior · Theory

What is a context manager, and how does the with statement work? How do you write your own context manager?

~4 min by voice

How to approach it

They're checking whether you understand the context manager protocol: that with guarantees setup and cleanup code around a block even when there's an exception, which methods make that work, and how to write your own manager as a class or with contextlib.

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-levelHow 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