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:
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:
| |
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:
| |
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:
| |
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.