What PEP introduced the 'with' statement for resource management?

The story behind the answer

PEP 343 introduced Python's with statement for resource management.

The proposal formalized a context-management mechanism: code inside a with block runs between an object's __enter__() and __exit__() methods. This lets a resource be acquired at the start and reliably released afterward, including when an exception interrupts the block. Opening files is the classic example: with open("notes.txt") as f: allows Python to close the file automatically.

Before with became available, programmers commonly used try/finally to guarantee cleanup. PEP 343 provided a clearer, reusable pattern that could work with files, locks, database connections, network sessions, and other resources. The underlying context-manager protocol also supports user-defined classes and the contextlib module.

The feature arrived in Python 2.5, released in 2006, and remains central to modern Python. PEP 8 is the style guide, PEP 20 describes the Zen of Python, and PEP 3000 concerned the Python 3 transition; none introduced resource-management syntax.

Source: Wikipedia · fact-checked Aug. 2026

Add question to a list

Choose a list to keep this question in: