Python: Handling closing of asynchronous coroutine properly

Home   »   Python: Handling closing of asynchronous coroutine properly

# https://www.python.org/dev/peps/pep-0525/
import asyncio


async def generate_numbers():
    i = 0
    while True:
        try:
            yield i
        except GeneratorExit:
            print("Closing")
            break
        i += 1

    print("Infinite loop finished")


async def main():
    numgen = generate_numbers()
    async for i in numgen:
        print(i)
        if i == 10:
            break
    await numgen.aclose()


asyncio.run(main())

Leave a Reply

Your email address will not be published. Required fields are marked *