Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / Python

contextlib.contextmanager

Decora una funzione generatrice con un solo yield come fabbrica di gestori with monouso.

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

Sintassi

@contextlib.contextmanager

Decora una funzione generatrice con un solo yield come fabbrica di gestori with monouso.

Ogni istanza del gestore generatore è monouso, mentre come decoratore crea un nuovo generatore a ogni chiamata della funzione decorata. Prima di yield avviene la preparazione e il valore viene associato ad as. Un errore del corpo rientra in yield ed è soppresso se il generatore lo cattura e termina normalmente. finally assicura la pulizia.

Qui closed precede handled.

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

Esempi

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")

Risultato

4
closed
handled

Qui closed precede handled.

Fonti