CKTIS / Python
contextlib.aclosing
Obalí objekt s metodou aclose() rozsahem async with.
Verze: Python 3.14; repository image, production runtime not attested
Syntaxe
async with contextlib.aclosing(thing) as resource:Obalí objekt s metodou aclose() rozsahem async with.
Vstup vrátí tentýž objekt a výstup čeká na aclose ve stejné úloze a kontextu. Proto break v async for uklidí generátor ještě před ukončením rozsahu. V příkladu následuje po 4 zpráva closed z finally.
Výjimka těla se obvykle šíří dál.
import asyncio
async def main():
from contextlib import aclosing
seen = []
async def stream():
try:
yield 1
yield 2
finally:
seen.append(asyncio.current_task())
async with aclosing(stream()) as it:
async for value in it:
break
assert seen == [asyncio.current_task()]
asyncio.run(main())
Příklady
import contextlib
import asyncio
async def items():
try:
yield 4
yield 9
finally:
print("closed")
async def main():
async with contextlib.aclosing(items()) as it:
async for item in it:
print(item)
break
asyncio.run(main())
Výsledek
4 closed
Výjimka těla se obvykle šíří dál.