Last Updated: May 22, 2026
Opening a file, acquiring a lock, or connecting to a database all share one shape: you grab a resource, do some work, then release the resource. If an exception jumps out of the middle, the release step has to run anyway, or you leak file handles, leave locks held, or strand connections. The with statement was built for exactly this pattern, and it's the canonical way to make cleanup exception-safe in Python. This chapter focuses on why with exists and how it cooperates with the exception machinery.