CKTIS / Python
contextlib.AbstractContextManager
Osnovni razred za sinhroni with ponuja `__enter__`, ki vrne upravljalnik.
Različica: Python 3.14; repository image, production runtime not attested
Sintaksa
class Scope(contextlib.AbstractContextManager): ...Osnovni razred za sinhroni with ponuja __enter__, ki vrne upravljalnik.
Podrazred opredeli __exit__, ki ob običajnem izhodu prejme tri None, sicer tip, objekt in sled izjeme. Tu vrne True samo za ValueError, zato se nato izpiše continued.
Druge izjeme se širijo naprej.
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]
Primeri
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")
Rezultat
True continued
Druge izjeme se širijo naprej.