Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Errors & context managersMiddleOccasionalPractical

How can you open multiple resources in a single `with` statement, and what does `contextlib.ExitStack` add for a dynamic number of them?

Answer

A single `with` statement can list several context managers separated by commas, or parenthesized across multiple lines since Python 3.10: `with open("a") as a, open("b") as b:`, and Python guarantees all of them are exited in reverse order even if one raises partway through setup. `contextlib.ExitStack` handles the case where the number of context managers is not known until runtime — you can call `stack.enter_context(cm)` in a loop, and `ExitStack` still guarantees every successfully entered context manager is exited correctly, in reverse order, even if a later one fails.

Strong answer includes

  • comma-separated or parenthesized with statements handle a fixed known set
  • all exited in reverse order even on partial failure
  • ExitStack handles a dynamic, runtime-determined number of context managers

Practical example

Python example
with ExitStack() as stack:
    files = [stack.enter_context(open(p)) for p in paths]

safely opens an arbitrary, runtime-determined number of files and guarantees they all close.

#context-managers#contextlib

Sources

contextlib — Utilities for with-statement contextsPython Software Foundation · Context manager helpers, including contextmanager and ExitStack