CKTIS / Python
contextlib.AbstractContextManager
La classe base per with sincrono fornisce `__enter__` che restituisce il gestore.
Versione: Python 3.14; repository image, production runtime not attested
Sintassi
class Scope(contextlib.AbstractContextManager): ...La classe base per with sincrono fornisce __enter__ che restituisce il gestore.
La sottoclasse definisce __exit__, che riceve tre None all’uscita normale oppure tipo, oggetto e traccia dell’eccezione. Qui restituisce True solo per ValueError e poi compare continued.
Le altre eccezioni si propagano.
from contextlib import AbstractContextManager
seen = []
class Scope(AbstractContextManager):
def __exit__(self, typ, exc, tb):
seen.append(typ)
return typ is KeyError
s = Scope()
with s as obj:
assert obj is s
with s:
raise KeyError
assert seen == [None, KeyError]
Esempi
import contextlib
class Scope(contextlib.AbstractContextManager):
def __exit__(self, kind, value, tb):
return kind is ValueError
scope = Scope()
with scope as obj:
print(obj is scope)
raise ValueError
print("continued")
Risultato
True continued
Le altre eccezioni si propagano.