CKTIS / Python
contextlib.AbstractContextManager
Die Basisklasse für synchrones with liefert ein `__enter__`, das den Manager zurückgibt.
Version: Python 3.14; repository image, production runtime not attested
Syntax
class Scope(contextlib.AbstractContextManager): ...Die Basisklasse für synchrones with liefert ein __enter__, das den Manager zurückgibt.
Die Unterklasse definiert __exit__, das normalerweise drei None und bei Fehlern Typ, Objekt und Traceback empfängt. Hier liefert es genau für ValueError True, sodass danach continued erscheint.
Andere Ausnahmen werden weitergegeben.
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]
Beispiele
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")
Ergebnis
True continued
Andere Ausnahmen werden weitergegeben.