Language Syntax

With — Python syntax

Enter a context manager, bind the enter result if requested, and call its exit hook when leaving after successful entry. A truthy exit result suppresses an exception. Multiple managers enter left to right and exit in reverse order. The as target is optional.

Formal Syntax & Structure

python syntaxpython
with context_expression as target:    suite

Parameters & Attributes

NameTypeDescription
context_expressionexpressionProduces a context manager.
targetassignment targetOptional binding for enter result.
suitestatement suiteProtected body.

Working Example

Example Snippetpython
from io import StringIOwith StringIO('hello') as stream:    value=stream.read()print((value,stream.closed))
Python Reference