Content · Programming · Python

Python Coordinate Multiple Open Resources Safely

Open several resources and clean them up in reverse order.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Open several resources and clean them up in reverse order.

What It Does and Why It Matters


ExitStack lets code enter an unknown number of context managers and keeps track of their cleanup callbacks. If acquiring resource three fails, the resources already entered will still close. Use a regular nested with when the resource count is fixed and small.

Stack cleanup works in last-in, first-out order.

Correct cleanup means resources are released when exceptions occur, not only on the success path.

Step-by-Step Example


Start with the complete example below. Read the inputs and predict what the final print statement will show before you run it.

from contextlib import ExitStack
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
    paths = [Path(folder) / f"part_{n}.txt" for n in range(2)]
    with ExitStack() as stack:
        streams = [stack.enter_context(open(p, "w", encoding="utf-8")) for p in paths]
        for n, stream in enumerate(streams):
            stream.write(f"record {n}")
    print([p.read_text(encoding="utf-8") for p in paths])

How the Code Works


  • The imports make these standard-library tools available: contextlib, pathlib, tempfile.
  • The loop advances through values one at a time. Note when the condition is checked and when the state changes.
  • The structured block controls error handling or resource lifetime, including what happens when an operation fails.
  • The print calls display the results. Compare these results with the method’s documented return type and the input used.

Expected output:

['record 0', 'record 1']

For the demonstrated inputs, Python displays "['record 0', 'record 1']". This result follows from the operation described above; change one input at a time to understand which rule matters.

What to Notice


Pay attention to the accepted input types, the returned value and the boundary behavior. Predict what changes if you replace the example input with an empty, zero, negative or missing value, where that value is meaningful for this operation.

If the task uses a library function, inspect its documented exceptions and return type before reusing it inside a larger function.

Where You Would Use This


This matters when working with files, locks, sockets and connections whose lifetime must be controlled. A reliable implementation defines ownership and releases resources on both successful and exceptional paths. Use a small with block before building a more complex manager.

Practice Exercise


Add a third file and verify all streams are closed when leaving ExitStack.

Before running your edited example, write down the result you expect. Then test at least one valid boundary or deliberately invalid value, using appropriate exception handling where necessary.

Reference: official Python documentation for the complete API contract and version notes.

Common Beginner Mistakes


  • Opening many resources without closing the already-open ones when a later open fails.
  • Releasing the resource only on the successful path rather than when an exception interrupts the block.

Key Takeaways


  • Open several resources and clean them up in reverse order.
  • ExitStack lets code enter an unknown number of context managers and keeps track of their cleanup callbacks.
  • Add a third file and verify all streams are closed when leaving ExitStack.
  • Correct cleanup means resources are released when exceptions occur, not only on the success path.
Share this resourceSend this page to someone who may find it useful.