CKTIS / Python
contextlib.AbstractContextManager
Osnovna klasa za sinkroni with daje `__enter__` koji vraća upravitelja.
Verzija: Python 3.14; repository image, production runtime not attested
Sintaksa
class Scope(contextlib.AbstractContextManager): ...Osnovna klasa za sinkroni with daje __enter__ koji vraća upravitelja.
Potklasa definira __exit__, koji pri uobičajenom izlazu prima tri None, inače tip, objekt i trag iznimke. Ovdje vraća True samo za ValueError pa se zatim ispisuje continued.
Ostale se iznimke šire dalje.
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]
Primjeri
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
Ostale se iznimke šire dalje.