Open this example in the interactive library
Source code
import asyncio
from contextlib import aclosing
async def stream():
try:
yield 'first'
yield 'second'
finally:
print('closed')
async def main():
async with aclosing(stream()) as source:
print(await anext(source))
asyncio.run(main())Sample output
first closed
