CKTIS / Python
contextlib.AbstractAsyncContextManager
Facilita l’implementazione di async with.
Versione: Python 3.14; repository image, production runtime not attested
Sintassi
class Scope(contextlib.AbstractAsyncContextManager): ...Facilita l’implementazione di async with.
Il __aenter__ ereditato restituisce self dopo await e la sottoclasse deve definire un __aexit__ asincrono. Riceve tre None al successo oppure tipo, eccezione e traccia. Un risultato vero sopprime l’eccezione.
Nell’esempio False lascia arrivare ValueError al gestore esterno.
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())
Esempi
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())
Risultato
True ValueError caught
Nell’esempio False lascia arrivare ValueError al gestore esterno.