Skip to the solution
MediumDSA12 min read

How do you use multiple context managers at once?

160 views

The problem

Question presented to candidate: "Say you need to read from one file and write to another, and hold a lock while you do it. How do you manage all three with with? And what if the number of files is only known at run time?"

What a strong answer should cover:

  • with a() as x, b() as y: is exactly equivalent to nesting one with inside another; the parenthesised, one-per-line form is official since Python 3.10.
  • Order: managers are entered left to right and exited right to left (last in, first out), so a later manager can use an earlier one.
  • Failure part-way: if a later __enter__ raises, the managers already entered are still exited; the one that failed is not.
  • Exceptions travel inside out: the innermost __exit__ sees the error first and can suppress it, and then outer managers see a clean exit.
  • contextlib.ExitStack for a dynamic number of managers: enter_context(), callback(), and pop_all() for all-or-nothing acquisition; AsyncExitStack for async with.
  • Look-alikes that are wrong: with (a, b) as t: makes a tuple, and with a and b: enters only one.

Clarifying questions expected:

  • Is the number of resources fixed at write time, or does it depend on input?
  • Must acquisition be all-or-nothing, and should the resources outlive the function that opens them?

Code / implementation expected: Yes β€” a comma-separated with showing enter/exit order, and an ExitStack loop over a list of resources.

  • context-manager
  • multiple

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read Β· 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonEnter and exit order, failures part-way, suppression and look-alikes
PythonExitStack: run-time lists, partial failure, callbacks and pop_all

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 107 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What is except* and ExceptionGroup in Python 3.11+?

Continue