Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Keyword with

Enter the context manager and optionally bind the value returned by `__enter__`.

Version: Python 3.14; repository image, production runtime not attested

Syntax

with manager as value:
    ...

Enter the context manager and optionally bind the value returned by __enter__.

Once entry succeeds, __exit__ runs when the suite is left, including by exception. A true return from __exit__ suppresses the exception being handled; a false return propagates it. Failure in __enter__ does not call that same manager’s __exit__. Multiple managers enter from left to right and exit in reverse order.

If a later entry fails, already entered managers unwind, beginning with the innermost one.

Examples

class Gate:
    def __enter__(self):
        return "inside"
    def __exit__(self, typ, val, tb):
        print(typ.__name__ if typ else "normal")
        return typ is ValueError
with Gate() as label:
    print(label)
    raise ValueError("handled")
print("continued")
from contextlib import contextmanager
trace = []
@contextmanager
def record(name, fail=False):
    trace.append("enter " + name)
    if fail:
        raise KeyError(name)
    try:
        yield
    finally:
        trace.append("exit " + name)
try:
    with record("A"), record("B"), record("C", True):
        raise AssertionError("body")
except KeyError:
    pass
assert trace == ["enter A", "enter B", "enter C", "exit B", "exit A"]

Result

inside
ValueError
continued

If a later entry fails, already entered managers unwind, beginning with the innermost one.

Sources