CKTIS / Python
contextlib.aclosing
Обхваща обект с метод aclose() в блок async with.
Версия: Python 3.14; repository image, production runtime not attested
Синтаксис
async with contextlib.aclosing(thing) as resource:Обхваща обект с метод aclose() в блок async with.
Входът връща същия обект, а изходът изчаква aclose в същата задача и контекст. Така break в async for почиства генератора преди напускането на обхвата. В примера след 4 идва closed от finally.
Изключение от тялото обичайно се предава нататък.
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())
Примери
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())
Резултат
4 closed
Изключение от тялото обичайно се предава нататък.