CKTIS / Python
contextlib.AsyncExitStack
Accumula pulizie sincrone e asincrone in una pila LIFO.
Versione: Python 3.14; repository image, production runtime not attested
Sintassi
async with contextlib.AsyncExitStack() as stack:Accumula pulizie sincrone e asincrone in una pila LIFO.
push_async_callback non sopprime eccezioni, mentre una funzione registrata con push_async_exit riceve i dati dell’eccezione e può sopprimerla con un risultato vero. pop_all trasferisce tutte le azioni senza eseguirle. enter_async_context attende l’ingresso e registra l’uscita, push_async_callback registra pulizia senza argomenti di eccezione. callback accetta funzioni ordinarie. Uscita o await aclose() esegue second prima di first.
Il risultato registrato tramite callback non sopprime eccezioni.
import asyncio
async def main():
from contextlib import AsyncExitStack
order = []
async def release(name):
order.append(name)
s = AsyncExitStack()
s.callback(order.append, "first")
s.push_async_callback(release, "second")
await s.aclose()
assert order == ["second", "first"]
asyncio.run(main())
import asyncio
async def main():
from contextlib import AsyncExitStack
seen = []
async def suppress_key(typ, exc, tb):
seen.append(typ)
return typ is KeyError
s = AsyncExitStack()
s.push_async_exit(suppress_key)
owner = s.pop_all()
await s.aclose()
assert not seen
async with owner:
raise KeyError
assert seen == [KeyError]
asyncio.run(main())
Esempi
import contextlib
import asyncio
async def release(label):
print(label)
async def main():
async with contextlib.AsyncExitStack() as stack:
stack.callback(print, "first")
stack.push_async_callback(release, "second")
asyncio.run(main())
Risultato
second first
Il risultato registrato tramite callback non sopprime eccezioni.