CKTIS / Python
contextlib.AbstractAsyncContextManager
Uľahčuje implementáciu príkazu async with.
Verzia: Python 3.14; repository image, production runtime not attested
Syntax
class Scope(contextlib.AbstractAsyncContextManager): ...Uľahčuje implementáciu príkazu async with.
Zdedené __aenter__ po await vráti self a podtrieda musí definovať asynchrónne __aexit__. Pri úspechu dostane tri None, inak typ, výnimku a zásobník. Pravdivý výsledok výnimku potlačí.
V príklade False dovolí zachytiť ValueError mimo bloku.
import asyncio
from contextlib import AbstractAsyncContextManager
seen = []
class Scope(AbstractAsyncContextManager):
async def __aexit__(self, typ, value, tb):
seen.append((typ, value, tb))
return False
async def main():
s = Scope()
async with s as obj:
assert obj is s
assert seen == [(None, None, None)]
asyncio.run(main())
Príklady
import contextlib
import asyncio
class Scope(contextlib.AbstractAsyncContextManager):
async def __aexit__(self, kind, value, tb):
print(kind.__name__ if kind is not None else "ok")
return False
async def main():
scope = Scope()
try:
async with scope as seen:
print(seen is scope)
raise ValueError
except ValueError:
print("caught")
asyncio.run(main())
Výsledok
True ValueError caught
V príklade False dovolí zachytiť ValueError mimo bloku.