Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Module contextlib

Build and compose context managers for scoped resources.

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

Syntax

@contextlib.contextmanager

Build and compose context managers for scoped resources.

A generator decorated by contextmanager yields exactly once, with setup before the yield and cleanup normally protected by finally. ExitStack unwinds registered callbacks in reverse order, including when the body raises.

The example records the order of cleanup around a handled exception.

Examples

import contextlib
trace = []
@contextlib.contextmanager
def scope():
    trace.append("enter")
    try:
        yield "active"
    finally:
        trace.append("leave")
try:
    with contextlib.ExitStack() as stack:
        stack.callback(trace.append, "last")
        trace.append(stack.enter_context(scope()))
        raise ValueError("stop")
except ValueError:
    pass
print(trace)

Result

['enter', 'active', 'leave', 'last']

The example records the order of cleanup around a handled exception.

Sources