Close Variable Python Input Files with contextlib.ExitStack

A report builder receives a list of text files at runtime. Opening them in a list comprehension and closing them only after processing leaves a cleanup gap: if the third open fails, the first two handles still need closing. contextlib.ExitStack lets each successful acquisition register its own cleanup immediately.

These examples use Python 3.10 or later. The helper deliberately keeps every input open together, which is useful when processing needs to alternate between inputs. For a simple concatenation, opening and processing one file at a time uses fewer handles.

Give the Group One Explicit Lifetime

Save this helper as input_group.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from contextlib import ExitStack, contextmanager


@contextmanager
def open_inputs(paths):
    with ExitStack() as stack:
        streams = []
        for path in paths:
            stream = stack.enter_context(open(path, "r", encoding="utf-8"))
            streams.append(stream)
        yield streams

enter_context() enters the file’s context manager and registers its exit method. Leaving the stack unwinds registrations in reverse order. A later open() failure therefore closes earlier inputs before propagating. File context managers also close their handles when processing raises inside the caller’s with block.

The wrapper yields only after all requested inputs have opened. Consult the ExitStack reference for registration and exception handling, and the contextmanager contract for how an exception in the caller resumes the generator.

Consume the Streams Inside the Block

Save this demonstration beside the helper and run it with Python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from pathlib import Path
from tempfile import TemporaryDirectory

from input_group import open_inputs

with TemporaryDirectory() as directory:
    root = Path(directory)
    first = root / "first.txt"
    second = root / "second.txt"
    first.write_text("alpha\nbeta\n", encoding="utf-8")
    second.write_text("gamma\n", encoding="utf-8")

    with open_inputs([first, second]) as streams:
        print([sum(1 for _ in stream) for stream in streams])
        print([stream.closed for stream in streams])
    print([stream.closed for stream in streams])
# [2, 1]
# [False, False]
# [True, True]

The list remains accessible afterward, but its file objects are closed. Finish iteration within the block. Returning a generator that will read these streams later moves the reads beyond the lifetime that protects them.

An empty path list yields an empty list. Repeated paths open separate streams with independent positions. Input order is preserved; the helper does not sort, deduplicate, or inspect filenames.

Verify a Later Open Failure

The following standalone test uses in-memory text streams and a patched open to observe closure directly. Save it as test_input_open_failure.py beside the helper:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
from io import StringIO
from unittest.mock import patch

from input_group import open_inputs

opened = [StringIO("alpha"), StringIO("beta")]
failure = FileNotFoundError("missing input")
entered_body = False

with patch("builtins.open", side_effect=[*opened, failure]) as mocked_open:
    try:
        with open_inputs(["first.txt", "second.txt", "missing.txt"]):
            entered_body = True
    except FileNotFoundError as exc:
        assert exc is failure
    else:
        raise AssertionError("missing input was accepted")

assert mocked_open.call_count == 3
assert not entered_body
assert all(stream.closed for stream in opened)
print("Partial acquisition cleanup passed.")

The test establishes that the caller never starts processing a partially opened group. It checks handle state rather than relying on garbage collection or on platform-specific rules for deleting open files.

Verify Processing and Decoding Failures

Save this as test_input_processing.py and run it beside the helper:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from pathlib import Path
from tempfile import TemporaryDirectory

from input_group import open_inputs

with TemporaryDirectory() as directory:
    root = Path(directory)
    good = root / "good.txt"
    bad = root / "bad.txt"
    good.write_text("ready\n", encoding="utf-8")
    bad.write_bytes(b"\xff")

    failure = RuntimeError("report failed")
    try:
        with open_inputs([good]) as streams:
            assert streams[0].read() == "ready\n"
            raise failure
    except RuntimeError as exc:
        assert exc is failure
    else:
        raise AssertionError("processing failure was suppressed")
    assert all(stream.closed for stream in streams)

    try:
        with open_inputs([good, bad]) as streams:
            streams[1].read()
    except UnicodeDecodeError:
        pass
    else:
        raise AssertionError("invalid UTF-8 was accepted")
    assert len(streams) == 2
    assert all(stream.closed for stream in streams)

with open_inputs([]) as streams:
    assert streams == []
print("Processing and decoding cleanup passed.")

Opening a text file does not prove that all its bytes can be decoded. Reading remains inside the managed lifetime so a decoding exception also triggers cleanup. The helper does not catch these failures or replace them with a successful empty report.

Keep Cleanup Separate from Rollback

Closing inputs does not undo output already written, uploads already sent, or rows already committed. Opening the complete group first prevents work from starting after a partial acquisition, but a later read can still fail. Design the report’s output commit separately if incomplete results must never become visible.

This helper also holds one handle per path until exit. Limit the group size according to the application’s resource budget; ExitStack does not impose a concurrency or handle limit. Keep the stack in a with statement instead of relying on its eventual garbage collection to run registered cleanup.