<p dir="ltr">Hi Yury et al,</p>
<p dir="ltr">Apologies for not participating in this discussion before -- unfortunately I've been dealing with some boring medical issues and haven't been able to contribute as much as early as I should have... But I do have two concerns, one minor and one not.</p>
<p dir="ltr">Minor comment: this is purely an aesthetic issue, but the PEP should probably have some discussion of the choice between "async yield" vs bare "yield" as the syntax. Arguments for "async yield" would be consistency with the other async syntax ("async for" etc.) and potentially reduced confusion about how inside an async def, "await" yields, and "yield" yields, but in totally different senses. Arguments for "yield" would be terseness, I guess. Probably this is just something for Guido to pick...</p>
<p dir="ltr">Major issue: I have serious concerns about the whole async finalizer design.</p>
<p dir="ltr">1) there is a very general problem of how to handle cleanup in async code, which isn't specific to async generators at all -- really any object that holds resources that need async cleanup has exactly the same issue. So the special purpose solution here makes me uncomfortable.</p>
<p dir="ltr">2) our understanding of this problem (resource cleanup in async code) is *really* immature. You can check the async-sig archives for some discussion -- I think it's safe to say that all the "experts" are extremely confused about this problem's shape/scope/best practices. I guess probably there are 10ish people who kind of understand the problem and 0 people who deeply understand it. (I was working on at least writing something up try and make the issue more accessible, but have not managed yet, which I feel bad about :-(.)  But given this, trying to freeze one particular strategy into the language on the 3.6 timeline raises a red flag for me.</p>
<p dir="ltr">3) specifically, I don't understand how the proposed solution in the pep can work reliably in the presence of non-prompt garbage collection (e.g. in the presence of cycles on cpython, or on pypy in general). What happens when the async generator object gets collected after the event loop exits? We could require event loops to force a full collection before exiting, but this is a rather uncomfortable coupling! (Do all python implementations even have a way to force a guaranteed-to-collect-ALL-garbage collection? What are the performance implications of async code triggering such full collections at inopportune times?) And even this didn't necessarily solve the problem, since async generators frames could still be "live" from the GC point of view, even if we know that their resources should be released. (E.g. consider an exception thrown from an async gen that propagates out of the event loop, so the event loop exits while the async gen's frame is pinned by the traceback object.)</p>
<p dir="ltr">Python in general has been moving towards more explicit/deterministic cleanup through "with" statements, and I think this is great. My feeling is that we should try to continue in this vein, rather than jumping through hoops to let people get away with sloppy coding that relies on __del__ and usually works except when it doesn't.</p>
<p dir="ltr">For example, what if we added an optional __abreak__ coroutine to the async iterator protocol, with the semantics that an "async for" will always either iterate to exhaustion, or else call __abreak__, i.e.</p>
<p dir="ltr"># new style code<br>
async for x in aiter:<br>
    ...</p>
<p dir="ltr">becomes sugar for</p>
<p dir="ltr"># 3.5 style code<br>
try:<br>
    async for x in aiter:<br>
        ...<br>
finally:<br>
    if for_loop_exited_early and hasattr(aiter, "___abreak__"):<br>
        await aiter.__abreak__(...)</p>
<p dir="ltr">Basically the idea here is that currently, what we should *really* be doing if we care about reliable+deterministic resource cleanup is never writing bare "for" loops but instead always writing</p>
<p dir="ltr">async with ... as aiter:<br>
    async for ... in aiter:<br>
        ...</p>
<p dir="ltr">But that's really tiresome and no one does it, so let's build the "with" into the for loop.</p>
<p dir="ltr">Of course there are cases where you want to reuse a single iterator object in multiple loops; this would look like:</p>
<p dir="ltr"># doing something clever, so we have to explicitly take charge of cleanup ourselves:<br>
async with ... as aiter:<br>
    # read header (= first non-comment line)<br>
    async for header in iterlib.unclosing(aiter):<br>
        if not header.startswith("#"):<br>
            break<br>
    # continue with same iterator to read body<br>
     async for line in iterlib.unclosing(aiter):<br>
         ...</p>
<p dir="ltr">where iterlib.unclosing returns a simple proxy object that passes through __anext__ and friends but swallows __abreak__ to make it a no-op.</p>
<p dir="ltr">Or maybe not, this isn't a fully worked out proposal :-). My main concern is that we don't rush to make a decision for 3.6, skip the hard work of considering different designs, and end up with something we regret in retrospect.</p>
<p dir="ltr">Some other options to consider:<br>
- add async generators to 3.6, but defer the full cleanup discussion for now -- so in 3.6 people will have to use "async with aclosing(aiter): ..." or whatever, but at least we can start getting experience with these objects now, and worry about making them more pleasant to use in the 3.7 time frame.</p>
<p dir="ltr">- defer the whole thing to 3.7. Obviously this would be really sad, but... To hold us over until then, it turns out that a library based solution is actually pretty ergonomic -- see <a href="https://github.com/njsmith/async_generator">https://github.com/njsmith/async_generator</a> . I should add asend/athrow/aclose (I think I have them on a branch), but otherwise it's pretty much as capable and easy to use as "real" async generators. So while I'd love to see these in the language, it doesn't feel super urgent to me.</p>
<p dir="ltr">-n</p>
<div class="gmail_extra"><br><div class="gmail_quote">On Aug 2, 2016 3:31 PM, "Yury Selivanov" <<a href="mailto:yselivanov.ml@gmail.com">yselivanov.ml@gmail.com</a>> wrote:<br type="attribution"><blockquote class="quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">Hi,<br>
<br>
This is a new PEP to add asynchronous generators to Python 3.6.  The PEP is also available at [1].<br>
<br>
There is a reference implementation [2] that supports everything that the PEP proposes to add.<br>
<br>
[1] <a href="https://www.python.org/dev/peps/pep-0525/" rel="noreferrer" target="_blank">https://www.python.org/dev/pep<wbr>s/pep-0525/</a><br>
<br>
[2] <a href="https://github.com/1st1/cpython/tree/async_gen" rel="noreferrer" target="_blank">https://github.com/1st1/cpytho<wbr>n/tree/async_gen</a><br>
<br>
Thank you!<br>
<br>
<br>
PEP: 525<br>
Title: Asynchronous Generators<br>
Version: $Revision$<br>
Last-Modified: $Date$<br>
Author: Yury Selivanov <<a href="mailto:yury@magic.io" target="_blank">yury@magic.io</a>><br>
Discussions-To: <<a href="mailto:python-dev@python.org" target="_blank">python-dev@python.org</a>><br>
Status: Draft<br>
Type: Standards Track<br>
Content-Type: text/x-rst<br>
Created: 28-Jul-2016<br>
Python-Version: 3.6<br>
Post-History: 02-Aug-2016<br>
<br>
<br>
Abstract<br>
========<br>
<br>
PEP 492 introduced support for native coroutines and ``async``/``await``<br>
syntax to Python 3.5.  It is proposed here to extend Python's<br>
asynchronous capabilities by adding support for<br>
*asynchronous generators*.<br>
<br>
<br>
Rationale and Goals<br>
===================<br>
<br>
Regular generators (introduced in PEP 255) enabled an elegant way of<br>
writing complex *data producers* and have them behave like an iterator.<br>
<br>
However, currently there is no equivalent concept for the *asynchronous<br>
iteration protocol* (``async for``).  This makes writing asynchronous<br>
data producers unnecessarily complex, as one must define a class that<br>
implements ``__aiter__`` and ``__anext__`` to be able to use it in<br>
an ``async for`` statement.<br>
<br>
Essentially, the goals and rationale for PEP 255, applied to the<br>
asynchronous execution case, hold true for this proposal as well.<br>
<br>
Performance is an additional point for this proposal: in our testing of<br>
the reference implementation, asynchronous generators are **2x** faster<br>
than an equivalent implemented as an asynchronous iterator.<br>
<br>
As an illustration of the code quality improvement, consider the<br>
following class that prints numbers with a given delay once iterated::<br>
<br>
    class Ticker:<br>
        """Yield numbers from 0 to `to` every `delay` seconds."""<br>
<br>
        def __init__(self, delay, to):<br>
            self.delay = delay<br>
            self.i = 0<br>
            <a href="http://self.to" rel="noreferrer" target="_blank">self.to</a> = to<br>
<br>
        def __aiter__(self):<br>
            return self<br>
<br>
        async def __anext__(self):<br>
            i = self.i<br>
            if i >= <a href="http://self.to" rel="noreferrer" target="_blank">self.to</a>:<br>
                raise StopAsyncIteration<br>
            self.i += 1<br>
            if i:<br>
                await asyncio.sleep(self.delay)<br>
            return i<br>
<br>
<br>
The same can be implemented as a much simpler asynchronous generator::<br>
<br>
    async def ticker(delay, to):<br>
        """Yield numbers from 0 to `to` every `delay` seconds."""<br>
        for i in range(to):<br>
            yield i<br>
            await asyncio.sleep(delay)<br>
<br>
<br>
Specification<br>
=============<br>
<br>
This proposal introduces the concept of *asynchronous generators* to<br>
Python.<br>
<br>
This specification presumes knowledge of the implementation of<br>
generators and coroutines in Python (PEP 342, PEP 380 and PEP 492).<br>
<br>
<br>
Asynchronous Generators<br>
-----------------------<br>
<br>
A Python *generator* is any function containing one or more ``yield``<br>
expressions::<br>
<br>
    def func():            # a function<br>
        return<br>
<br>
    def genfunc():         # a generator function<br>
        yield<br>
<br>
We propose to use the same approach to define<br>
*asynchronous generators*::<br>
<br>
    async def coro():      # a coroutine function<br>
        await smth()<br>
<br>
    async def asyncgen():  # an asynchronous generator function<br>
        await smth()<br>
        yield 42<br>
<br>
The result of calling an *asynchronous generator function* is<br>
an *asynchronous generator object*, which implements the asynchronous<br>
iteration protocol defined in PEP 492.<br>
<br>
It is a ``SyntaxError`` to have a non-empty ``return`` statement in an<br>
asynchronous generator.<br>
<br>
<br>
Support for Asynchronous Iteration Protocol<br>
------------------------------<wbr>-------------<br>
<br>
The protocol requires two special methods to be implemented:<br>
<br>
1. An ``__aiter__`` method returning an *asynchronous iterator*.<br>
2. An ``__anext__`` method returning an *awaitable* object, which uses<br>
   ``StopIteration`` exception to "yield" values, and<br>
   ``StopAsyncIteration`` exception to signal the end of the iteration.<br>
<br>
Asynchronous generators define both of these methods.  Let's manually<br>
iterate over a simple asynchronous generator::<br>
<br>
    async def genfunc():<br>
        yield 1<br>
        yield 2<br>
<br>
    gen = genfunc()<br>
<br>
    assert gen.__aiter__() is gen<br>
<br>
    assert await gen.__anext__() == 1<br>
    assert await gen.__anext__() == 2<br>
<br>
    await gen.__anext__()  # This line will raise StopAsyncIteration.<br>
<br>
<br>
Finalization<br>
------------<br>
<br>
PEP 492 requires an event loop or a scheduler to run coroutines.<br>
Because asynchronous generators are meant to be used from coroutines,<br>
they also require an event loop to run and finalize them.<br>
<br>
Asynchronous generators can have ``try..finally`` blocks, as well as<br>
``async with``.  It is important to provide a guarantee that, even<br>
when partially iterated, and then garbage collected, generators can<br>
be safely finalized.  For example::<br>
<br>
    async def square_series(con, to):<br>
        async with con.transaction():<br>
            cursor = con.cursor(<br>
                'SELECT generate_series(0, $1) AS i', to)<br>
            async for row in cursor:<br>
                yield row['i'] ** 2<br>
<br>
    async for i in square_series(con, 1000):<br>
        if i == 100:<br>
            break<br>
<br>
The above code defines an asynchronous generator that uses<br>
``async with`` to iterate over a database cursor in a transaction.<br>
The generator is then iterated over with ``async for``, which interrupts<br>
the iteration at some point.<br>
<br>
The ``square_series()`` generator will then be garbage collected,<br>
and without a mechanism to asynchronously close the generator, Python<br>
interpreter would not be able to do anything.<br>
<br>
To solve this problem we propose to do the following:<br>
<br>
1. Implement an ``aclose`` method on asynchronous generators<br>
   returning a special *awaitable*.  When awaited it<br>
   throws a ``GeneratorExit`` into the suspended generator and<br>
   iterates over it until either a ``GeneratorExit`` or<br>
   a ``StopAsyncIteration`` occur.<br>
<br>
   This is very similar to what the ``close()`` method does to regular<br>
   Python generators, except that an event loop is required to execute<br>
   ``aclose()``.<br>
<br>
2. Raise a ``RuntimeError``, when an asynchronous generator executes<br>
   a ``yield`` expression in its ``finally`` block (using ``await``<br>
   is fine, though)::<br>
<br>
        async def gen():<br>
            try:<br>
                yield<br>
            finally:<br>
                await asyncio.sleep(1)   # Can use 'await'.<br>
<br>
                yield                    # Cannot use 'yield',<br>
                                         # this line will trigger a<br>
                                         # RuntimeError.<br>
<br>
3. Add two new methods to the ``sys`` module:<br>
   ``set_asyncgen_finalizer()`` and ``get_asyncgen_finalizer()``.<br>
<br>
The idea behind ``sys.set_asyncgen_finalizer()<wbr>`` is to allow event<br>
loops to handle generators finalization, so that the end user<br>
does not need to care about the finalization problem, and it just<br>
works.<br>
<br>
When an asynchronous generator is iterated for the first time,<br>
it stores a reference to the current finalizer.  If there is none,<br>
a ``RuntimeError`` is raised.  This provides a strong guarantee that<br>
every asynchronous generator object will always have a finalizer<br>
installed by the correct event loop.<br>
<br>
When an asynchronous generator is about to be garbage collected,<br>
it calls its cached finalizer.  The assumption is that the finalizer<br>
will schedule an ``aclose()`` call with the loop that was active<br>
when the iteration started.<br>
<br>
For instance, here is how asyncio is modified to allow safe<br>
finalization of asynchronous generators::<br>
<br>
   # asyncio/base_events.py<br>
<br>
   class BaseEventLoop:<br>
<br>
       def run_forever(self):<br>
           ...<br>
           old_finalizer = sys.get_asyncgen_finalizer()<br>
           sys.set_asyncgen_finalizer(se<wbr>lf._finalize_asyncgen)<br>
           try:<br>
               ...<br>
           finally:<br>
               sys.set_asyncgen_finalizer(ol<wbr>d_finalizer)<br>
               ...<br>
<br>
       def _finalize_asyncgen(self, gen):<br>
           self.create_task(gen.aclose()<wbr>)<br>
<br>
``sys.set_asyncgen_finalizer()<wbr>`` is thread-specific, so several event<br>
loops running in parallel threads can use it safely.<br>
<br>
<br>
Asynchronous Generator Object<br>
-----------------------------<br>
<br>
The object is modeled after the standard Python generator object.<br>
Essentially, the behaviour of asynchronous generators is designed<br>
to replicate the behaviour of synchronous generators, with the only<br>
difference in that the API is asynchronous.<br>
<br>
The following methods and properties are defined:<br>
<br>
1. ``agen.__aiter__()``: Returns ``agen``.<br>
<br>
2. ``agen.__anext__()``: Returns an *awaitable*, that performs one<br>
   asynchronous generator iteration when awaited.<br>
<br>
3. ``agen.asend(val)``: Returns an *awaitable*, that pushes the<br>
   ``val`` object in the ``agen`` generator.  When the ``agen`` has<br>
   not yet been iterated, ``val`` must be ``None``.<br>
<br>
   Example::<br>
<br>
       async def gen():<br>
           await asyncio.sleep(0.1)<br>
           v = yield 42<br>
           print(v)<br>
           await asyncio.sleep(0.2)<br>
<br>
       g = gen()<br>
<br>
       await g.asend(None)      # Will return 42 after sleeping<br>
                                # for 0.1 seconds.<br>
<br>
       await g.asend('hello')   # Will print 'hello' and<br>
                                # raise StopAsyncIteration<br>
                                # (after sleeping for 0.2 seconds.)<br>
<br>
4. ``agen.athrow(typ, [val, [tb]])``: Returns an *awaitable*, that<br>
   throws an exception into the ``agen`` generator.<br>
<br>
   Example::<br>
<br>
       async def gen():<br>
           try:<br>
               await asyncio.sleep(0.1)<br>
               yield 'hello'<br>
           except ZeroDivisionError:<br>
               await asyncio.sleep(0.2)<br>
               yield 'world'<br>
<br>
       g = gen()<br>
       v = await g.asend(None)<br>
       print(v)                # Will print 'hello' after<br>
                               # sleeping for 0.1 seconds.<br>
<br>
       v = await g.athrow(ZeroDivisionError)<br>
       print(v)                # Will print 'world' after<br>
                               $ sleeping 0.2 seconds.<br>
<br>
5. ``agen.aclose()``: Returns an *awaitable*, that throws a<br>
   ``GeneratorExit`` exception into the generator.  The *awaitable* can<br>
   either return a yielded value, if ``agen`` handled the exception,<br>
   or ``agen`` will be closed and the exception will propagate back<br>
   to the caller.<br>
<br>
6. ``agen.__name__`` and ``agen.__qualname__``: readable and writable<br>
   name and qualified name attributes.<br>
<br>
7. ``agen.ag_await``: The object that ``agen`` is currently *awaiting*<br>
   on, or ``None``.  This is similar to the currently available<br>
   ``gi_yieldfrom`` for generators and ``cr_await`` for coroutines.<br>
<br>
8. ``agen.ag_frame``, ``agen.ag_running``, and ``agen.ag_code``:<br>
   defined in the same way as similar attributes of standard generators.<br>
<br>
``StopIteration`` and ``StopAsyncIteration`` are not propagated out of<br>
asynchronous generators, and are replaced with a ``RuntimeError``.<br>
<br>
<br>
Implementation Details<br>
----------------------<br>
<br>
Asynchronous generator object (``PyAsyncGenObject``) shares the<br>
struct layout with ``PyGenObject``.  In addition to that, the<br>
reference implementation introduces three new objects:<br>
<br>
1. ``PyAsyncGenASend``: the awaitable object that implements<br>
   ``__anext__`` and ``asend()`` methods.<br>
<br>
2. ``PyAsyncGenAThrow``: the awaitable object that implements<br>
   ``athrow()`` and ``aclose()`` methods.<br>
<br>
3. ``_PyAsyncGenWrappedValue``: every directly yielded object from an<br>
   asynchronous generator is implicitly boxed into this structure.  This<br>
   is how the generator implementation can separate objects that are<br>
   yielded using regular iteration protocol from objects that are<br>
   yielded using asynchronous iteration protocol.<br>
<br>
``PyAsyncGenASend`` and ``PyAsyncGenAThrow`` are awaitables (they have<br>
``__await__`` methods returning ``self``) and are coroutine-like objects<br>
(implementing ``__iter__``, ``__next__``, ``send()`` and ``throw()``<br>
methods).  Essentially, they control how asynchronous generators are<br>
iterated:<br>
<br>
.. image:: pep-0525-1.png<br>
   :align: center<br>
   :width: 80%<br>
<br>
<br>
PyAsyncGenASend and PyAsyncGenAThrow<br>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^<wbr>^^^^^^<br>
<br>
``PyAsyncGenASend`` is a coroutine-like object that drives ``__anext__``<br>
and ``asend()`` methods and implements the asynchronous iteration<br>
protocol.<br>
<br>
``agen.asend(val)`` and ``agen.__anext__()`` return instances of<br>
``PyAsyncGenASend`` (which hold references back to the parent<br>
``agen`` object.)<br>
<br>
The data flow is defined as follows:<br>
<br>
1. When ``PyAsyncGenASend.send(val)`` is called for the first time,<br>
   ``val`` is pushed to the parent ``agen`` object (using existing<br>
   facilities of ``PyGenObject``.)<br>
<br>
   Subsequent iterations over the ``PyAsyncGenASend`` objects, push<br>
   ``None`` to ``agen``.<br>
<br>
   When a ``_PyAsyncGenWrappedValue`` object is yielded, it<br>
   is unboxed, and a ``StopIteration`` exception is raised with the<br>
   unwrapped value as an argument.<br>
<br>
2. When ``PyAsyncGenASend.throw(*exc)`<wbr>` is called for the first time,<br>
   ``*exc`` is throwed into the parent ``agen`` object.<br>
<br>
   Subsequent iterations over the ``PyAsyncGenASend`` objects, push<br>
   ``None`` to ``agen``.<br>
<br>
   When a ``_PyAsyncGenWrappedValue`` object is yielded, it<br>
   is unboxed, and a ``StopIteration`` exception is raised with the<br>
   unwrapped value as an argument.<br>
<br>
3. ``return`` statements in asynchronous generators raise<br>
   ``StopAsyncIteration`` exception, which is propagated through<br>
   ``PyAsyncGenASend.send()`` and ``PyAsyncGenASend.throw()`` methods.<br>
<br>
``PyAsyncGenAThrow`` is very similar to ``PyAsyncGenASend``. The only<br>
difference is that ``PyAsyncGenAThrow.send()``, when called first time,<br>
throws an exception into the parent ``agen`` object (instead of pushing<br>
a value into it.)<br>
<br>
<br>
New Standard Library Functions and Types<br>
------------------------------<wbr>----------<br>
<br>
1. ``types.AsyncGeneratorType`` -- type of asynchronous generator<br>
   object.<br>
<br>
2. ``sys.set_asyncgen_finalizer()<wbr>`` and ``sys.get_asyncgen_finalizer()<wbr>``<br>
   methods to set up asynchronous generators finalizers in event loops.<br>
<br>
3. ``inspect.isasyncgen()`` and ``inspect.isasyncgenfunction()<wbr>``<br>
   introspection functions.<br>
<br>
<br>
Backwards Compatibility<br>
-----------------------<br>
<br>
The proposal is fully backwards compatible.<br>
<br>
In Python 3.5 it is a ``SyntaxError`` to define an ``async def``<br>
function with a ``yield`` expression inside, therefore it's safe to<br>
introduce asynchronous generators in 3.6.<br>
<br>
<br>
Performance<br>
===========<br>
<br>
Regular Generators<br>
------------------<br>
<br>
There is no performance degradation for regular generators.<br>
The following micro benchmark runs at the same speed on CPython with<br>
and without asynchronous generators::<br>
<br>
    def gen():<br>
        i = 0<br>
        while i < 100000000:<br>
            yield i<br>
            i += 1<br>
<br>
    list(gen())<br>
<br>
<br>
Improvements over asynchronous iterators<br>
------------------------------<wbr>----------<br>
<br>
The following micro-benchmark shows that asynchronous generators<br>
are about **2.3x faster** than asynchronous iterators implemented in<br>
pure Python::<br>
<br>
    N = 10 ** 7<br>
<br>
    async def agen():<br>
        for i in range(N):<br>
            yield i<br>
<br>
    class AIter:<br>
        def __init__(self):<br>
            self.i = 0<br>
<br>
        def __aiter__(self):<br>
            return self<br>
<br>
        async def __anext__(self):<br>
            i = self.i<br>
            if i >= N:<br>
                raise StopAsyncIteration<br>
            self.i += 1<br>
            return i<br>
<br>
<br>
Design Considerations<br>
=====================<br>
<br>
<br>
``aiter()`` and ``anext()`` builtins<br>
------------------------------<wbr>------<br>
<br>
Originally, PEP 492 defined ``__aiter__`` as a method that should<br>
return an *awaitable* object, resulting in an asynchronous iterator.<br>
<br>
However, in CPython 3.5.2, ``__aiter__`` was redefined to return<br>
asynchronous iterators directly.  To avoid breaking backwards<br>
compatibility, it was decided that Python 3.6 will support both<br>
ways: ``__aiter__`` can still return an *awaitable* with<br>
a ``DeprecationWarning`` being issued.<br>
<br>
Because of this dual nature of ``__aiter__`` in Python 3.6, we cannot<br>
add a synchronous implementation of ``aiter()`` built-in. Therefore,<br>
it is proposed to wait until Python 3.7.<br>
<br>
<br>
Asynchronous list/dict/set comprehensions<br>
------------------------------<wbr>-----------<br>
<br>
Syntax for asynchronous comprehensions is unrelated to the asynchronous<br>
generators machinery, and should be considered in a separate PEP.<br>
<br>
<br>
Asynchronous ``yield from``<br>
---------------------------<br>
<br>
While it is theoretically possible to implement ``yield from`` support<br>
for asynchronous generators, it would require a serious redesign of the<br>
generators implementation.<br>
<br>
``yield from`` is also less critical for asynchronous generators, since<br>
there is no need provide a mechanism of implementing another coroutines<br>
protocol on top of coroutines.  And to compose asynchronous generators a<br>
simple ``async for`` loop can be used::<br>
<br>
    async def g1():<br>
        yield 1<br>
        yield 2<br>
<br>
    async def g2():<br>
        async for v in g1():<br>
            yield v<br>
<br>
<br>
Why the ``asend()`` and ``athrow()`` methods are necessary<br>
------------------------------<wbr>----------------------------<br>
<br>
They make it possible to implement concepts similar to<br>
``contextlib.contextmanager`` using asynchronous generators.<br>
For instance, with the proposed design, it is possible to implement<br>
the following pattern::<br>
<br>
    @async_context_manager<br>
    async def ctx():<br>
        await open()<br>
        try:<br>
            yield<br>
        finally:<br>
            await close()<br>
<br>
    async with ctx():<br>
        await ...<br>
<br>
Another reason is that it is possible to push data and throw exceptions<br>
into asynchronous generators using the object returned from<br>
``__anext__`` object, but it is hard to do that correctly. Adding<br>
explicit ``asend()`` and ``athrow()`` will pave a safe way to<br>
accomplish that.<br>
<br>
In terms of implementation, ``asend()`` is a slightly more generic<br>
version of ``__anext__``, and ``athrow()`` is very similar to<br>
``aclose()``.  Therefore having these methods defined for asynchronous<br>
generators does not add any extra complexity.<br>
<br>
<br>
Example<br>
=======<br>
<br>
A working example with the current reference implementation (will<br>
print numbers from 0 to 9 with one second delay)::<br>
<br>
    async def ticker(delay, to):<br>
        for i in range(to):<br>
            yield i<br>
            await asyncio.sleep(delay)<br>
<br>
<br>
    async def run():<br>
        async for i in ticker(1, 10):<br>
            print(i)<br>
<br>
<br>
    import asyncio<br>
    loop = asyncio.get_event_loop()<br>
    try:<br>
        loop.run_until_complete(run())<br>
    finally:<br>
        loop.close()<br>
<br>
<br>
Implementation<br>
==============<br>
<br>
The complete reference implementation is available at [1]_.<br>
<br>
<br>
References<br>
==========<br>
<br>
.. [1] <a href="https://github.com/1st1/cpython/tree/async_gen" rel="noreferrer" target="_blank">https://github.com/1st1/cpytho<wbr>n/tree/async_gen</a><br>
<br>
<br>
Copyright<br>
=========<br>
<br>
This document has been placed in the public domain.<br>
<br>
..<br>
   Local Variables:<br>
   mode: indented-text<br>
   indent-tabs-mode: nil<br>
   sentence-end-double-space: t<br>
   fill-column: 70<br>
   coding: utf-8<br>
   End:<br>
<br>
______________________________<wbr>_________________<br>
Python-ideas mailing list<br>
<a href="mailto:Python-ideas@python.org" target="_blank">Python-ideas@python.org</a><br>
<a href="https://mail.python.org/mailman/listinfo/python-ideas" rel="noreferrer" target="_blank">https://mail.python.org/mailma<wbr>n/listinfo/python-ideas</a><br>
Code of Conduct: <a href="http://python.org/psf/codeofconduct/" rel="noreferrer" target="_blank">http://python.org/psf/codeofco<wbr>nduct/</a><br>
</blockquote></div><br></div>