CKTIS / Python
contextlib.aclosing
Encadre par async with un objet doté de aclose().
Version : Python 3.14; repository image, production runtime not attested
Syntaxe
async with contextlib.aclosing(thing) as resource:Encadre par async with un objet doté de aclose().
L’entrée renvoie le même objet et la sortie attend aclose dans la même tâche et le même contexte. Un break dans async for déclenche ainsi le nettoyage du générateur avant la fin de la portée. Ici 4 précède closed venant de finally.
Une exception du corps se propage normalement.
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())
Exemples
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())
Résultat
4 closed
Une exception du corps se propage normalement.