Checking your account

You can read the lesson while its saved answers and constructions load. Learning controls will open once that work is ready.

Context Managers and Resource Cleanup

The with Statement and Resource Lifetimes

BOTIE

Opening and closing a resource creates a paired obligation. Repeating the same cleanup structure throughout a program makes it easy to omit a failure path. Python’s try/finally can express that obligation, but every caller would still need to write the pattern correctly.

PEP 343, created in 2005 for Python 2.5, introduced the with statement to factor out common try/finally patterns. A context manager supplies the entry and exit behavior, while the body still contains the work being performed. The resource-lifetime rules become visible at the place where the resource is used.

Sources for this history