CKTIS / Python
contextlib.AsyncExitStack
Zbira sinhrona in asinhrona čiščenja na skladu LIFO.
Različica: Python 3.14; repository image, production runtime not attested
Sintaksa
async with contextlib.AsyncExitStack() as stack:Zbira sinhrona in asinhrona čiščenja na skladu LIFO.
push_async_callback ne zatre izjeme, funkcija, dodana s push_async_exit, pa dobi podatke o izjemi in jo lahko zatre z resničnim rezultatom. pop_all prenese vsa dejanja brez izvedbe. enter_async_context počaka na vstop in zabeleži izstop, push_async_callback doda čiščenje brez argumentov izjeme. callback sprejme običajne funkcije. Izhod ali await aclose() izvede second pred first.
Rezultat funkcije, dodane s callback, ne zatre izjeme.
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())
Primeri
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())
Rezultat
second first
Rezultat funkcije, dodane s callback, ne zatre izjeme.