Keywords and Control Flow

with — Context-managed resource lifetime

Enter a context manager, execute a block, and invoke its exit method when leaving the block after successful entry. The optional target receives the value returned by __enter__, not necessarily the manager itself. On an exception the exit method receives exception information; a truthy result suppresses that exception. Normal completion supplies three None arguments. Multiple managers enter from left to right and exit in reverse order. If entry fails, that manager is not exited, but previously entered managers are unwound. Use async with for the asynchronous protocol.

Formal Syntax & Structure

python syntaxpython
with manager as target:    suite
with first as a, second as b:    suite

Working Example

Example Snippetpython
from io import StringIO
with StringIO("pen\nbook\n") as source:    print([line.strip() for line in source])print(source.closed)
Python Reference