Interview Prep/Python for DevOps/Exceptions, context managers, files & logging

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.

All Python for DevOps questions Roadmap: Python for automation

More on Exceptions, context managers, files & logging