PythiloLesson 1 of 12 · progress kept in this browser

Unwind partially acquired resources

Acquiring several resources is a transaction of its own. If the third acquisition fails, the first two still need cleanup, in reverse order. An ExitStack records ownership as each acquisition succeeds. Registering cleanup only after every acquisition works leaves a leak on the failure path.

This exercise accepts context-manager factories so the tests can fail a specific acquisition without files or network access. The same ownership pattern applies to files, temporary directories and database sessions. A context manager should return a resource only after it owns the cleanup obligation.

from contextlib import ExitStack
log = []
with ExitStack() as stack:
    stack.callback(log.append, "first")
    stack.callback(log.append, "last")
print(log)
Your task

Implement acquire_all(factories, use). Enter each context manager in order, call use(resources) once, return its result and close everything in reverse order even if acquisition or use raises.