Koskamo

Context managers and the with statement

Document v1 · published by Koskamo editorial · updated 2026-10-04

Original source

The with statement wraps the execution of a block with methods defined by a context manager, encapsulating common try…except…finally usage patterns for convenient reuse. The context expression is evaluated to obtain a context manager, whose enter() and exit() methods are loaded; enter() is invoked, and if an as target was included its return value is assigned to it. The language reference guarantees that if enter() returns without an error, exit() will always be called. After the suite runs, exit() is invoked: if an exception caused the suite to exit, its type, value, and traceback are passed as arguments, otherwise three None arguments are supplied. When the suite exits due to an exception, a false return from exit() reraises the exception and a true return suppresses it; for exits not caused by an exception the return value is ignored. A single with statement may carry several comma-separated items. Scope: Python 3. Reviewed October 4, 2026.

Source and provenance

Original source
docs.python.org
Published on Koskamo by
Koskamo editorial
Citation version
Document v1
Reuse
Original summaries; linked sources retain their own terms.

The original source supplies the underlying information. Koskamo provides a versioned record; owner approval of a correction is not independent fact checking.