Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

contextlib.contextmanager

Builds a context-manager factory from a generator that yields the managed value exactly once.

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

Syntax

@contextlib.contextmanager

Builds a context-manager factory from a generator that yields the managed value exactly once.

Code after the yield performs cleanup; a finally block ensures that cleanup also happens after an exception.

Decorate a generator function that yields exactly once to create one-shot managers for with. Setup runs before yield; the yielded value is bound by as. A body error is injected at yield and is suppressed if the generator catches it and finishes normally. Use finally for cleanup and re-raise to propagate. The example prints closed before handled. The generator manager instance is single-use. As a decorator it creates a new generator for each call of the decorated function.

from contextlib import contextmanager
seen = []
@contextmanager
def scope():
    try:
        yield "open"
    except LookupError:
        seen.append("handled")
        raise
    finally:
        seen.append("closed")
try:
    with scope() as x:
        assert x == "open"
        raise KeyError
except KeyError:
    assert seen == ["handled", "closed"]
@scope()
def check():
    return 3
assert check() == check() == 3

Examples

import contextlib
@contextlib.contextmanager
def measure():
    try:
        yield 4
    finally:
        print("closed")

try:
    with measure() as value:
        print(value)
        raise ValueError
except ValueError:
    print("handled")

Result

4
closed
handled

Decorate a generator function that yields exactly once to create one-shot managers for with. Setup runs before yield; the yielded value is bound by as. A body error is injected at yield and is suppressed if the generator catches it and finishes normally. Use finally for cleanup and re-raise to propagate. The example prints closed before handled. The generator manager instance is single-use. As a decorator it creates a new generator for each call of the decorated function.

Sources