CKTIS / Python
contextlib.aclosing
Objekt z metodo aclose() ovije v območje async with.
Različica: Python 3.14; repository image, production runtime not attested
Sintaksa
async with contextlib.aclosing(thing) as resource:Objekt z metodo aclose() ovije v območje async with.
Vstop vrne isti objekt, izhod pa počaka na aclose v istem opravilu in kontekstu. Tako break v async for počisti generator pred izhodom iz območja. V primeru za 4 sledi closed iz finally.
Izjema telesa se običajno širi naprej.
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())
Primeri
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())
Rezultat
4 closed
Izjema telesa se običajno širi naprej.