In Python, what does the 'with' statement provide for resource management?
Answer
context manager
Answer
context manager
In Python, what does the “with” statement provide for resource management? It provides a context manager. A context manager defines setup and cleanup behavior around a block of code, allowing resources such as files, locks, and database connections to be handled reliably.
The “with” statement calls the context manager’s __enter__ method before the block runs and its __exit__ method afterward. Cleanup still occurs when the block raises an exception, which is why this pattern is safer than manually opening a resource and hoping every execution path reaches a close operation. The file-opening function returns a familiar example of a context manager.
A common mix-up is calling “with” an exception handler. It does not replace try/except: exceptions may still propagate unless the context manager’s cleanup logic suppresses them or the block includes explicit handling. It is also different from garbage collection, which concerns automatic memory reclamation. Python’s context-management protocol was formalized through PEP 343, introduced for Python 2.5.
Source: Wikipedia · fact-checked Aug. 2026