CKTIS / Python
contextlib.AsyncExitStack
Skuplja sinkrona i asinkrona čišćenja na stogu LIFO.
Verzija: Python 3.14; repository image, production runtime not attested
Sintaksa
async with contextlib.AsyncExitStack() as stack:Skuplja sinkrona i asinkrona čišćenja na stogu LIFO.
push_async_callback ne potiskuje iznimku, dok funkcija dodana preko push_async_exit dobiva podatke o iznimci i može je potisnuti istinitim rezultatom. pop_all prenosi sve radnje bez izvođenja. enter_async_context čeka ulaz i registrira izlaz, push_async_callback dodaje čišćenje bez argumenata iznimke. callback prihvaća obične funkcije. Izlaz ili await aclose() izvršava second prije first.
Rezultat funkcije dodane putem callback ne potiskuje iznimku.
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())
Primjeri
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 putem callback ne potiskuje iznimku.