CKTIS / Python
contextlib.AbstractContextManager
La classe de base pour with synchrone fournit `__enter__` qui renvoie le gestionnaire.
Version : Python 3.14; repository image, production runtime not attested
Syntaxe
class Scope(contextlib.AbstractContextManager): ...La classe de base pour with synchrone fournit __enter__ qui renvoie le gestionnaire.
La sous-classe définit __exit__, qui reçoit normalement trois None, ou le type, l’objet et la trace de l’exception. Ici il renvoie True exactement pour ValueError et continued est affiché ensuite.
Les autres exceptions se propagent.
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]
Exemples
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")
Résultat
True continued
Les autres exceptions se propagent.