CKTIS / Python
contextlib.AbstractAsyncContextManager
Erleichtert die Implementierung von async with.
Version: Python 3.14; repository image, production runtime not attested
Syntax
class Scope(contextlib.AbstractAsyncContextManager): ...Erleichtert die Implementierung von async with.
Das geerbte __aenter__ liefert nach await self, die Unterklasse muss ein asynchrones __aexit__ implementieren. Es erhält bei Erfolg dreimal None, sonst Typ, Ausnahme und Traceback. Ein wahrer Rückgabewert unterdrückt die Ausnahme.
False lässt hier ValueError den äußeren Handler erreichen.
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())
Beispiele
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())
Ergebnis
True ValueError caught
False lässt hier ValueError den äußeren Handler erreichen.