Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Python Context Managers

HardPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Python Context Managers. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

python里的with怎么实现的

Asked in the coding round 1 stage. Same interviewer, Python internals.

Task

Implement context_manager_trace(should_raise, suppress_exception) using a custom context manager. It must record the order of __enter__, the with-body, and __exit__. If the body raises ValueError, __exit__ decides whether the exception is suppressed. The function must return the trace, including propagated when the exception escapes the with statement.

Contract

Input: two booleans. Output: a list of strings.

Constraints

  • should_raise and suppress_exception are booleans
  • The with-body raises either no exception or one ValueError
  • The returned trace contains at most four strings

Function Signature

def context_manager_trace(should_raise, suppress_exception):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output