If you’re using Python
context managers,
you can use contextlib.ExitStack
to work with many of them at once.
A context manager that is designed to make it easy to programmatically combine other context managers and cleanup functions, especially those that are optional or otherwise driven by input data.
contextlib.ExitStack
documentationBasically, this allows you to use multiple context managers without knowing the list before runtime.
I’m annoyed to report that I have built more than one custom implementation of this functionality
without knowing that it was in the standard library,
and I basically finished a 1500 word blog post and 120 line example program describing my most recent solution.
The only reason I even discovered the version in the standard library was
when I started writing tests to verify my code before publishing it,
Claude 3.5 Sonnet helpfully told me I should use contextlib.ExitStack
for this instead.