[Python-ideas] PEP 525: Asynchronous Generators

Vladimir Rutsky rutsky.vladimir at gmail.com
Tue Aug 9 13:24:23 EDT 2016


Hi Yury,

Thank you for posting this PEP!
As an asyncio-based libraries user, author and contributor I
appreciate that topic of easy-writing of asynchronous generators is
being covered now.
I like how simple writing of async generators will be with this PEP,
same with consequent functionality (e.g. async context wrappers).

It's great that with this PEP it would be possible to write simple
async data processing wrappers without a knowledge of a single special
method
(__aiter__, __anext__, __aenter__, __aexit__) using same patterns as
regular Python user would use in synchronous code:

@async_context_manager
async def connection(uri):
    conn = await connect(uri)
    try:
        yield conn
    finally:
        conn.close()
        await conn.wait_closed()

async def query_data(conn, q):
    cursor = await conn.query(q)
    try:
        row = await cursor.fetch_row()
        while row is not None:
            yield row
            row = await cursor.fetch_row()
    finally:
        cursor.close()
        await cursor.wait_closed()

async with connection(uri) as conn:
    async for item in query_data(q):
        print(item)

And this is as simple as in synchronous code, but made asynchronous.


Can you explain details of canceling of asend and await coroutines?

Consider following example:

async def gen():
    zero = yield 0
    asyncio.sleep(10)
    one = yield 1

async def f(loop):
    g = gen()

    await g.asend(None)

    send_task = loop.create_task(g.asend('zero'))
    send_task.cancel()

    # What is the state of g now?
    # Can I receive one from g? Or cancel() will lead to
CancelledError throw from asyncio.sleep(10)?
    one = g.asend('one')

Will canceling of asend() task result in canceling of generator?


Thanks,
Vladimir Rutsky


More information about the Python-ideas mailing list