CKTIS / Python
contextlib.ContextDecorator
Permette di usare come decoratore un gestore con `__enter__` e `__exit__`.
Versione: Python 3.14; repository image, production runtime not attested
Sintassi
class Scope(contextlib.ContextDecorator): ...Permette di usare come decoratore un gestore con __enter__ e __exit__.
Ogni chiamata alla funzione ha un ingresso e un’uscita e __exit__ conserva la possibilità di sopprimere eccezioni. Il gestore deve sopportare usi ripetuti.
Nell’esempio enter ed exit circondano run e il chiamante riceve 4.
from contextlib import ContextDecorator
log = []
class Scope(ContextDecorator):
def __enter__(self): log.append("enter")
def __exit__(self, *info): log.append(info[0])
@Scope()
def double(x): return x * 2
assert (double(2), double(3)) == (4, 6)
assert log == ["enter", None, "enter", None]
Esempi
import contextlib
class Scope(contextlib.ContextDecorator):
def __enter__(self): print("enter")
def __exit__(self, *args): print("exit")
@Scope()
def run(): return 4
print(run())
Risultato
enter exit 4
Nell’esempio enter ed exit circondano run e il chiamante riceve 4.