CKTIS / Python
contextlib.aclosing
Racchiude un oggetto dotato di aclose() in un ambito async with.
Versione: Python 3.14; repository image, production runtime not attested
Sintassi
async with contextlib.aclosing(thing) as resource:Racchiude un oggetto dotato di aclose() in un ambito async with.
All’ingresso restituisce lo stesso oggetto e all’uscita attende aclose nello stesso task e contesto. Un break in async for fa quindi pulire il generatore prima dell’uscita. Qui a 4 segue closed dal finally.
Un’eccezione del corpo normalmente si propaga.
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())
Esempi
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())
Risultato
4 closed
Un’eccezione del corpo normalmente si propaga.