CKTIS / Python
contextlib.aclosing
Ensures that asynchronous cleanup is awaited when a managed resource leaves its scope.
Version: Python 3.14; repository image, production runtime not attested
Syntax
async with contextlib.aclosing(thing) as resource:Ensures that asynchronous cleanup is awaited when a managed resource leaves its scope.
Breaking out of an asynchronous generator loop still runs its cleanup at the end of the managed block.
Adapt an object that offers aclose() to async with. Entry hands back the same object; exit awaits its aclose in the same task and context. This makes early break from async iteration deterministic. The sample emits 4, then closed runs in the generator's finally before control leaves the scope. Body exceptions normally propagate.
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())
Examples
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())
Result
4 closed
Adapt an object that offers aclose() to async with. Entry hands back the same object; exit awaits its aclose in the same task and context. This makes early break from async iteration deterministic. The sample emits 4, then closed runs in the generator's finally before control leaves the scope. Body exceptions normally propagate.