What does `contextlib.ExitStack` solve?
AdvancedConceptExceptions, context managers, files & logging
Answer
It manages a dynamic number of context managers, for example opening one SSH connection per host where the host list is only known at runtime, and guarantees every one that opened is closed, in reverse order, even if a later one fails.
from contextlib import ExitStack
with ExitStack() as stack:
conns = [stack.enter_context(Connection(h)) for h in hosts]
for c in conns:
c.run("uptime")
It also supports stack.callback(fn, *args) for arbitrary cleanup.
More on Exceptions, context managers, files & logging
How does `try` / `except` / `else` / `finally` work?BeginnerWhy is a bare `except:` (or `except Exception: pass`) dangerous?BeginnerWhat is exception chaining, and what is `raise ... from`?IntermediateWhen should you define custom exception classes?IntermediateWhat is the EAFP vs LBYL style, and which does Python prefer?IntermediateHow does a `with` statement work, and why use it for files?Beginner