CKTIS / Python
contextlib.aclosing
Objekt s metodom aclose() obuhvaća opsegom async with.
Verzija: Python 3.14; repository image, production runtime not attested
Sintaksa
async with contextlib.aclosing(thing) as resource:Objekt s metodom aclose() obuhvaća opsegom async with.
Ulaz vraća isti objekt, a izlaz čeka aclose u istom zadatku i kontekstu. Tako break u async for čisti generator prije napuštanja opsega. U primjeru nakon 4 slijedi closed iz finally.
Iznimka tijela obično se širi dalje.
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())
Primjeri
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
Iznimka tijela obično se širi dalje.