Manage Dynamic Resource Lifetimes in Python with ExitStack
A normal with statement works best when you know the resources before the block starts: with open("input.csv", "rb") as source, open("output.csv", "wb") as target: ... The structure is clear because both files are known in advance. Python enters each context manager and guarantees that their exit logic runs when the block finishes, including when an exception leaves the block.