CKTIS / Python
contextlib.AbstractContextManager
De basisklasse voor synchrone with levert `__enter__`, dat de beheerder teruggeeft.
Versie: Python 3.14; repository image, production runtime not attested
Syntax
class Scope(contextlib.AbstractContextManager): ...De basisklasse voor synchrone with levert __enter__, dat de beheerder teruggeeft.
De subklasse definieert __exit__, dat bij normaal verlaten drie keer None krijgt en anders type, object en traceback. Hier geeft het alleen voor ValueError True zodat daarna continued verschijnt.
Andere uitzonderingen gaan door.
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]
Voorbeelden
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")
Resultaat
True continued
Andere uitzonderingen gaan door.