CINXE.COM

PEP 525 – Asynchronous Generators | peps.python.org

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="color-scheme" content="light dark"> <title>PEP 525 – Asynchronous Generators | peps.python.org</title> <link rel="shortcut icon" href="../_static/py.png"> <link rel="canonical" href="https://peps.python.org/pep-0525/"> <link rel="stylesheet" href="../_static/style.css" type="text/css"> <link rel="stylesheet" href="../_static/mq.css" type="text/css"> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" media="(prefers-color-scheme: light)" id="pyg-light"> <link rel="stylesheet" href="../_static/pygments_dark.css" type="text/css" media="(prefers-color-scheme: dark)" id="pyg-dark"> <link rel="alternate" type="application/rss+xml" title="Latest PEPs" href="https://peps.python.org/peps.rss"> <meta property="og:title" content='PEP 525 – Asynchronous Generators | peps.python.org'> <meta property="og:description" content="PEP 492 introduced support for native coroutines and async/await syntax to Python 3.5. It is proposed here to extend Python’s asynchronous capabilities by adding support for asynchronous generators."> <meta property="og:type" content="website"> <meta property="og:url" content="https://peps.python.org/pep-0525/"> <meta property="og:site_name" content="Python Enhancement Proposals (PEPs)"> <meta property="og:image" content="https://peps.python.org/_static/og-image.png"> <meta property="og:image:alt" content="Python PEPs"> <meta property="og:image:width" content="200"> <meta property="og:image:height" content="200"> <meta name="description" content="PEP 492 introduced support for native coroutines and async/await syntax to Python 3.5. It is proposed here to extend Python’s asynchronous capabilities by adding support for asynchronous generators."> <meta name="theme-color" content="#3776ab"> </head> <body> <svg xmlns="http://www.w3.org/2000/svg" style="display: none;"> <symbol id="svg-sun-half" viewBox="0 0 24 24" pointer-events="all"> <title>Following system colour scheme</title> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <circle cx="12" cy="12" r="9"></circle> <path d="M12 3v18m0-12l4.65-4.65M12 14.3l7.37-7.37M12 19.6l8.85-8.85"></path> </svg> </symbol> <symbol id="svg-moon" viewBox="0 0 24 24" pointer-events="all"> <title>Selected dark colour scheme</title> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M12 3c.132 0 .263 0 .393 0a7.5 7.5 0 0 0 7.92 12.446a9 9 0 1 1 -8.313 -12.454z"></path> </svg> </symbol> <symbol id="svg-sun" viewBox="0 0 24 24" pointer-events="all"> <title>Selected light colour scheme</title> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <circle cx="12" cy="12" r="5"></circle> <line x1="12" y1="1" x2="12" y2="3"></line> <line x1="12" y1="21" x2="12" y2="23"></line> <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line> <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line> <line x1="1" y1="12" x2="3" y2="12"></line> <line x1="21" y1="12" x2="23" y2="12"></line> <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line> <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line> </svg> </symbol> </svg> <script> document.documentElement.dataset.colour_scheme = localStorage.getItem("colour_scheme") || "auto" </script> <section id="pep-page-section"> <header> <h1>Python Enhancement Proposals</h1> <ul class="breadcrumbs"> <li><a href="https://www.python.org/" title="The Python Programming Language">Python</a> &raquo; </li> <li><a href="../pep-0000/">PEP Index</a> &raquo; </li> <li>PEP 525</li> </ul> <button id="colour-scheme-cycler" onClick="setColourScheme(nextColourScheme())"> <svg aria-hidden="true" class="colour-scheme-icon-when-auto"><use href="#svg-sun-half"></use></svg> <svg aria-hidden="true" class="colour-scheme-icon-when-dark"><use href="#svg-moon"></use></svg> <svg aria-hidden="true" class="colour-scheme-icon-when-light"><use href="#svg-sun"></use></svg> <span class="visually-hidden">Toggle light / dark / auto colour theme</span> </button> </header> <article> <section id="pep-content"> <h1 class="page-title">PEP 525 – Asynchronous Generators</h1> <dl class="rfc2822 field-list simple"> <dt class="field-odd">Author<span class="colon">:</span></dt> <dd class="field-odd">Yury Selivanov &lt;yury&#32;&#97;t&#32;edgedb.com&gt;</dd> <dt class="field-even">Discussions-To<span class="colon">:</span></dt> <dd class="field-even"><a class="reference external" href="https://mail.python.org/archives/list/python-dev&#64;python.org/">Python-Dev list</a></dd> <dt class="field-odd">Status<span class="colon">:</span></dt> <dd class="field-odd"><abbr title="Accepted and implementation complete, or no longer active">Final</abbr></dd> <dt class="field-even">Type<span class="colon">:</span></dt> <dd class="field-even"><abbr title="Normative PEP with a new feature for Python, implementation change for CPython or interoperability standard for the ecosystem">Standards Track</abbr></dd> <dt class="field-odd">Created<span class="colon">:</span></dt> <dd class="field-odd">28-Jul-2016</dd> <dt class="field-even">Python-Version<span class="colon">:</span></dt> <dd class="field-even">3.6</dd> <dt class="field-odd">Post-History<span class="colon">:</span></dt> <dd class="field-odd">02-Aug-2016, 23-Aug-2016, 01-Sep-2016, 06-Sep-2016</dd> </dl> <hr class="docutils" /> <section id="contents"> <details><summary>Table of Contents</summary><ul class="simple"> <li><a class="reference internal" href="#abstract">Abstract</a></li> <li><a class="reference internal" href="#rationale-and-goals">Rationale and Goals</a></li> <li><a class="reference internal" href="#specification">Specification</a><ul> <li><a class="reference internal" href="#asynchronous-generators">Asynchronous Generators</a></li> <li><a class="reference internal" href="#support-for-asynchronous-iteration-protocol">Support for Asynchronous Iteration Protocol</a></li> <li><a class="reference internal" href="#finalization">Finalization</a></li> <li><a class="reference internal" href="#asyncio">asyncio</a></li> <li><a class="reference internal" href="#asynchronous-generator-object">Asynchronous Generator Object</a></li> <li><a class="reference internal" href="#implementation-details">Implementation Details</a><ul> <li><a class="reference internal" href="#pyasyncgenasend-and-pyasyncgenathrow">PyAsyncGenASend and PyAsyncGenAThrow</a></li> </ul> </li> <li><a class="reference internal" href="#new-standard-library-functions-and-types">New Standard Library Functions and Types</a></li> <li><a class="reference internal" href="#backwards-compatibility">Backwards Compatibility</a></li> </ul> </li> <li><a class="reference internal" href="#performance">Performance</a><ul> <li><a class="reference internal" href="#regular-generators">Regular Generators</a></li> <li><a class="reference internal" href="#improvements-over-asynchronous-iterators">Improvements over asynchronous iterators</a></li> </ul> </li> <li><a class="reference internal" href="#design-considerations">Design Considerations</a><ul> <li><a class="reference internal" href="#aiter-and-anext-builtins"><code class="docutils literal notranslate"><span class="pre">aiter()</span></code> and <code class="docutils literal notranslate"><span class="pre">anext()</span></code> builtins</a></li> <li><a class="reference internal" href="#asynchronous-list-dict-set-comprehensions">Asynchronous list/dict/set comprehensions</a></li> <li><a class="reference internal" href="#asynchronous-yield-from">Asynchronous <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code></a></li> <li><a class="reference internal" href="#why-the-asend-and-athrow-methods-are-necessary">Why the <code class="docutils literal notranslate"><span class="pre">asend()</span></code> and <code class="docutils literal notranslate"><span class="pre">athrow()</span></code> methods are necessary</a></li> </ul> </li> <li><a class="reference internal" href="#example">Example</a></li> <li><a class="reference internal" href="#acceptance">Acceptance</a></li> <li><a class="reference internal" href="#implementation">Implementation</a></li> <li><a class="reference internal" href="#references">References</a></li> <li><a class="reference internal" href="#acknowledgments">Acknowledgments</a></li> <li><a class="reference internal" href="#copyright">Copyright</a></li> </ul> </details></section> <section id="abstract"> <h2><a class="toc-backref" href="#abstract" role="doc-backlink">Abstract</a></h2> <p><a class="pep reference internal" href="../pep-0492/" title="PEP 492 – Coroutines with async and await syntax">PEP 492</a> introduced support for native coroutines and <code class="docutils literal notranslate"><span class="pre">async</span></code>/<code class="docutils literal notranslate"><span class="pre">await</span></code> syntax to Python 3.5. It is proposed here to extend Python’s asynchronous capabilities by adding support for <em>asynchronous generators</em>.</p> </section> <section id="rationale-and-goals"> <h2><a class="toc-backref" href="#rationale-and-goals" role="doc-backlink">Rationale and Goals</a></h2> <p>Regular generators (introduced in <a class="pep reference internal" href="../pep-0255/" title="PEP 255 – Simple Generators">PEP 255</a>) enabled an elegant way of writing complex <em>data producers</em> and have them behave like an iterator.</p> <p>However, currently there is no equivalent concept for the <em>asynchronous iteration protocol</em> (<code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code>). This makes writing asynchronous data producers unnecessarily complex, as one must define a class that implements <code class="docutils literal notranslate"><span class="pre">__aiter__</span></code> and <code class="docutils literal notranslate"><span class="pre">__anext__</span></code> to be able to use it in an <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> statement.</p> <p>Essentially, the goals and rationale for <a class="pep reference internal" href="../pep-0255/" title="PEP 255 – Simple Generators">PEP 255</a>, applied to the asynchronous execution case, hold true for this proposal as well.</p> <p>Performance is an additional point for this proposal: in our testing of the reference implementation, asynchronous generators are <strong>2x</strong> faster than an equivalent implemented as an asynchronous iterator.</p> <p>As an illustration of the code quality improvement, consider the following class that prints numbers with a given delay once iterated:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">Ticker</span><span class="p">:</span> <span class="w"> </span><span class="sd">&quot;&quot;&quot;Yield numbers from 0 to `to` every `delay` seconds.&quot;&quot;&quot;</span> <span class="k">def</span><span class="w"> </span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">delay</span><span class="p">,</span> <span class="n">to</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">delay</span> <span class="o">=</span> <span class="n">delay</span> <span class="bp">self</span><span class="o">.</span><span class="n">i</span> <span class="o">=</span> <span class="mi">0</span> <span class="bp">self</span><span class="o">.</span><span class="n">to</span> <span class="o">=</span> <span class="n">to</span> <span class="k">def</span><span class="w"> </span><span class="fm">__aiter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span> <span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="fm">__anext__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">i</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">i</span> <span class="k">if</span> <span class="n">i</span> <span class="o">&gt;=</span> <span class="bp">self</span><span class="o">.</span><span class="n">to</span><span class="p">:</span> <span class="k">raise</span> <span class="ne">StopAsyncIteration</span> <span class="bp">self</span><span class="o">.</span><span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span> <span class="k">if</span> <span class="n">i</span><span class="p">:</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">delay</span><span class="p">)</span> <span class="k">return</span> <span class="n">i</span> </pre></div> </div> <p>The same can be implemented as a much simpler asynchronous generator:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">ticker</span><span class="p">(</span><span class="n">delay</span><span class="p">,</span> <span class="n">to</span><span class="p">):</span> <span class="w"> </span><span class="sd">&quot;&quot;&quot;Yield numbers from 0 to `to` every `delay` seconds.&quot;&quot;&quot;</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">to</span><span class="p">):</span> <span class="k">yield</span> <span class="n">i</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="n">delay</span><span class="p">)</span> </pre></div> </div> </section> <section id="specification"> <h2><a class="toc-backref" href="#specification" role="doc-backlink">Specification</a></h2> <p>This proposal introduces the concept of <em>asynchronous generators</em> to Python.</p> <p>This specification presumes knowledge of the implementation of generators and coroutines in Python (<a class="pep reference internal" href="../pep-0342/" title="PEP 342 – Coroutines via Enhanced Generators">PEP 342</a>, <a class="pep reference internal" href="../pep-0380/" title="PEP 380 – Syntax for Delegating to a Subgenerator">PEP 380</a> and <a class="pep reference internal" href="../pep-0492/" title="PEP 492 – Coroutines with async and await syntax">PEP 492</a>).</p> <section id="asynchronous-generators"> <h3><a class="toc-backref" href="#asynchronous-generators" role="doc-backlink">Asynchronous Generators</a></h3> <p>A Python <em>generator</em> is any function containing one or more <code class="docutils literal notranslate"><span class="pre">yield</span></code> expressions:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">func</span><span class="p">():</span> <span class="c1"># a function</span> <span class="k">return</span> <span class="k">def</span><span class="w"> </span><span class="nf">genfunc</span><span class="p">():</span> <span class="c1"># a generator function</span> <span class="k">yield</span> </pre></div> </div> <p>We propose to use the same approach to define <em>asynchronous generators</em>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">coro</span><span class="p">():</span> <span class="c1"># a coroutine function</span> <span class="k">await</span> <span class="n">smth</span><span class="p">()</span> <span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">asyncgen</span><span class="p">():</span> <span class="c1"># an asynchronous generator function</span> <span class="k">await</span> <span class="n">smth</span><span class="p">()</span> <span class="k">yield</span> <span class="mi">42</span> </pre></div> </div> <p>The result of calling an <em>asynchronous generator function</em> is an <em>asynchronous generator object</em>, which implements the asynchronous iteration protocol defined in <a class="pep reference internal" href="../pep-0492/" title="PEP 492 – Coroutines with async and await syntax">PEP 492</a>.</p> <p>It is a <code class="docutils literal notranslate"><span class="pre">SyntaxError</span></code> to have a non-empty <code class="docutils literal notranslate"><span class="pre">return</span></code> statement in an asynchronous generator.</p> </section> <section id="support-for-asynchronous-iteration-protocol"> <h3><a class="toc-backref" href="#support-for-asynchronous-iteration-protocol" role="doc-backlink">Support for Asynchronous Iteration Protocol</a></h3> <p>The protocol requires two special methods to be implemented:</p> <ol class="arabic simple"> <li>An <code class="docutils literal notranslate"><span class="pre">__aiter__</span></code> method returning an <em>asynchronous iterator</em>.</li> <li>An <code class="docutils literal notranslate"><span class="pre">__anext__</span></code> method returning an <em>awaitable</em> object, which uses <code class="docutils literal notranslate"><span class="pre">StopIteration</span></code> exception to “yield” values, and <code class="docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code> exception to signal the end of the iteration.</li> </ol> <p>Asynchronous generators define both of these methods. Let’s manually iterate over a simple asynchronous generator:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">genfunc</span><span class="p">():</span> <span class="k">yield</span> <span class="mi">1</span> <span class="k">yield</span> <span class="mi">2</span> <span class="n">gen</span> <span class="o">=</span> <span class="n">genfunc</span><span class="p">()</span> <span class="k">assert</span> <span class="n">gen</span><span class="o">.</span><span class="fm">__aiter__</span><span class="p">()</span> <span class="ow">is</span> <span class="n">gen</span> <span class="k">assert</span> <span class="k">await</span> <span class="n">gen</span><span class="o">.</span><span class="fm">__anext__</span><span class="p">()</span> <span class="o">==</span> <span class="mi">1</span> <span class="k">assert</span> <span class="k">await</span> <span class="n">gen</span><span class="o">.</span><span class="fm">__anext__</span><span class="p">()</span> <span class="o">==</span> <span class="mi">2</span> <span class="k">await</span> <span class="n">gen</span><span class="o">.</span><span class="fm">__anext__</span><span class="p">()</span> <span class="c1"># This line will raise StopAsyncIteration.</span> </pre></div> </div> </section> <section id="finalization"> <h3><a class="toc-backref" href="#finalization" role="doc-backlink">Finalization</a></h3> <p><a class="pep reference internal" href="../pep-0492/" title="PEP 492 – Coroutines with async and await syntax">PEP 492</a> requires an event loop or a scheduler to run coroutines. Because asynchronous generators are meant to be used from coroutines, they also require an event loop to run and finalize them.</p> <p>Asynchronous generators can have <code class="docutils literal notranslate"><span class="pre">try..finally</span></code> blocks, as well as <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code>. It is important to provide a guarantee that, even when partially iterated, and then garbage collected, generators can be safely finalized. For example:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">square_series</span><span class="p">(</span><span class="n">con</span><span class="p">,</span> <span class="n">to</span><span class="p">):</span> <span class="k">async</span> <span class="k">with</span> <span class="n">con</span><span class="o">.</span><span class="n">transaction</span><span class="p">():</span> <span class="n">cursor</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">(</span> <span class="s1">&#39;SELECT generate_series(0, $1) AS i&#39;</span><span class="p">,</span> <span class="n">to</span><span class="p">)</span> <span class="k">async</span> <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">cursor</span><span class="p">:</span> <span class="k">yield</span> <span class="n">row</span><span class="p">[</span><span class="s1">&#39;i&#39;</span><span class="p">]</span> <span class="o">**</span> <span class="mi">2</span> <span class="k">async</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">square_series</span><span class="p">(</span><span class="n">con</span><span class="p">,</span> <span class="mi">1000</span><span class="p">):</span> <span class="k">if</span> <span class="n">i</span> <span class="o">==</span> <span class="mi">100</span><span class="p">:</span> <span class="k">break</span> </pre></div> </div> <p>The above code defines an asynchronous generator that uses <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> to iterate over a database cursor in a transaction. The generator is then iterated over with <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code>, which interrupts the iteration at some point.</p> <p>The <code class="docutils literal notranslate"><span class="pre">square_series()</span></code> generator will then be garbage collected, and without a mechanism to asynchronously close the generator, Python interpreter would not be able to do anything.</p> <p>To solve this problem we propose to do the following:</p> <ol class="arabic"> <li>Implement an <code class="docutils literal notranslate"><span class="pre">aclose</span></code> method on asynchronous generators returning a special <em>awaitable</em>. When awaited it throws a <code class="docutils literal notranslate"><span class="pre">GeneratorExit</span></code> into the suspended generator and iterates over it until either a <code class="docutils literal notranslate"><span class="pre">GeneratorExit</span></code> or a <code class="docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code> occur.<p>This is very similar to what the <code class="docutils literal notranslate"><span class="pre">close()</span></code> method does to regular Python generators, except that an event loop is required to execute <code class="docutils literal notranslate"><span class="pre">aclose()</span></code>.</p> </li> <li>Raise a <code class="docutils literal notranslate"><span class="pre">RuntimeError</span></code>, when an asynchronous generator executes a <code class="docutils literal notranslate"><span class="pre">yield</span></code> expression in its <code class="docutils literal notranslate"><span class="pre">finally</span></code> block (using <code class="docutils literal notranslate"><span class="pre">await</span></code> is fine, though):<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">gen</span><span class="p">():</span> <span class="k">try</span><span class="p">:</span> <span class="k">yield</span> <span class="k">finally</span><span class="p">:</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="c1"># Can use &#39;await&#39;.</span> <span class="k">yield</span> <span class="c1"># Cannot use &#39;yield&#39;,</span> <span class="c1"># this line will trigger a</span> <span class="c1"># RuntimeError.</span> </pre></div> </div> </li> <li>Add two new methods to the <code class="docutils literal notranslate"><span class="pre">sys</span></code> module: <code class="docutils literal notranslate"><span class="pre">set_asyncgen_hooks()</span></code> and <code class="docutils literal notranslate"><span class="pre">get_asyncgen_hooks()</span></code>.</li> </ol> <p>The idea behind <code class="docutils literal notranslate"><span class="pre">sys.set_asyncgen_hooks()</span></code> is to allow event loops to intercept asynchronous generators iteration and finalization, so that the end user does not need to care about the finalization problem, and everything just works.</p> <p><code class="docutils literal notranslate"><span class="pre">sys.set_asyncgen_hooks()</span></code> accepts two arguments:</p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">firstiter</span></code>: a callable which will be called when an asynchronous generator is iterated for the first time.</li> <li><code class="docutils literal notranslate"><span class="pre">finalizer</span></code>: a callable which will be called when an asynchronous generator is about to be GCed.</li> </ul> <p>When an asynchronous generator is iterated for the first time, it stores a reference to the current <em>finalizer</em>.</p> <p>When an asynchronous generator is about to be garbage collected, it calls its cached <em>finalizer</em>. The assumption is that the finalizer will schedule an <code class="docutils literal notranslate"><span class="pre">aclose()</span></code> call with the loop that was active when the iteration started.</p> <p>For instance, here is how asyncio is modified to allow safe finalization of asynchronous generators:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># asyncio/base_events.py</span> <span class="k">class</span><span class="w"> </span><span class="nc">BaseEventLoop</span><span class="p">:</span> <span class="k">def</span><span class="w"> </span><span class="nf">run_forever</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="o">...</span> <span class="n">old_hooks</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">get_asyncgen_hooks</span><span class="p">()</span> <span class="n">sys</span><span class="o">.</span><span class="n">set_asyncgen_hooks</span><span class="p">(</span><span class="n">finalizer</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">_finalize_asyncgen</span><span class="p">)</span> <span class="k">try</span><span class="p">:</span> <span class="o">...</span> <span class="k">finally</span><span class="p">:</span> <span class="n">sys</span><span class="o">.</span><span class="n">set_asyncgen_hooks</span><span class="p">(</span><span class="o">*</span><span class="n">old_hooks</span><span class="p">)</span> <span class="o">...</span> <span class="k">def</span><span class="w"> </span><span class="nf">_finalize_asyncgen</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">gen</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">create_task</span><span class="p">(</span><span class="n">gen</span><span class="o">.</span><span class="n">aclose</span><span class="p">())</span> </pre></div> </div> <p>The second argument, <code class="docutils literal notranslate"><span class="pre">firstiter</span></code>, allows event loops to maintain a weak set of asynchronous generators instantiated under their control. This makes it possible to implement “shutdown” mechanisms to safely finalize all open generators and close the event loop.</p> <p><code class="docutils literal notranslate"><span class="pre">sys.set_asyncgen_hooks()</span></code> is thread-specific, so several event loops running in parallel threads can use it safely.</p> <p><code class="docutils literal notranslate"><span class="pre">sys.get_asyncgen_hooks()</span></code> returns a namedtuple-like structure with <code class="docutils literal notranslate"><span class="pre">firstiter</span></code> and <code class="docutils literal notranslate"><span class="pre">finalizer</span></code> fields.</p> </section> <section id="asyncio"> <h3><a class="toc-backref" href="#asyncio" role="doc-backlink">asyncio</a></h3> <p>The asyncio event loop will use <code class="docutils literal notranslate"><span class="pre">sys.set_asyncgen_hooks()</span></code> API to maintain a weak set of all scheduled asynchronous generators, and to schedule their <code class="docutils literal notranslate"><span class="pre">aclose()</span></code> coroutine methods when it is time for generators to be GCed.</p> <p>To make sure that asyncio programs can finalize all scheduled asynchronous generators reliably, we propose to add a new event loop coroutine method <code class="docutils literal notranslate"><span class="pre">loop.shutdown_asyncgens()</span></code>. The method will schedule all currently open asynchronous generators to close with an <code class="docutils literal notranslate"><span class="pre">aclose()</span></code> call.</p> <p>After calling the <code class="docutils literal notranslate"><span class="pre">loop.shutdown_asyncgens()</span></code> method, the event loop will issue a warning whenever a new asynchronous generator is iterated for the first time. The idea is that after requesting all asynchronous generators to be shutdown, the program should not execute code that iterates over new asynchronous generators.</p> <p>An example of how <code class="docutils literal notranslate"><span class="pre">shutdown_asyncgens</span></code> coroutine should be used:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span> <span class="n">loop</span><span class="o">.</span><span class="n">run_forever</span><span class="p">()</span> <span class="k">finally</span><span class="p">:</span> <span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">loop</span><span class="o">.</span><span class="n">shutdown_asyncgens</span><span class="p">())</span> <span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> </pre></div> </div> </section> <section id="asynchronous-generator-object"> <h3><a class="toc-backref" href="#asynchronous-generator-object" role="doc-backlink">Asynchronous Generator Object</a></h3> <p>The object is modeled after the standard Python generator object. Essentially, the behaviour of asynchronous generators is designed to replicate the behaviour of synchronous generators, with the only difference in that the API is asynchronous.</p> <p>The following methods and properties are defined:</p> <ol class="arabic"> <li><code class="docutils literal notranslate"><span class="pre">agen.__aiter__()</span></code>: Returns <code class="docutils literal notranslate"><span class="pre">agen</span></code>.</li> <li><code class="docutils literal notranslate"><span class="pre">agen.__anext__()</span></code>: Returns an <em>awaitable</em>, that performs one asynchronous generator iteration when awaited.</li> <li><code class="docutils literal notranslate"><span class="pre">agen.asend(val)</span></code>: Returns an <em>awaitable</em>, that pushes the <code class="docutils literal notranslate"><span class="pre">val</span></code> object in the <code class="docutils literal notranslate"><span class="pre">agen</span></code> generator. When the <code class="docutils literal notranslate"><span class="pre">agen</span></code> has not yet been iterated, <code class="docutils literal notranslate"><span class="pre">val</span></code> must be <code class="docutils literal notranslate"><span class="pre">None</span></code>.<p>Example:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">gen</span><span class="p">():</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">0.1</span><span class="p">)</span> <span class="n">v</span> <span class="o">=</span> <span class="k">yield</span> <span class="mi">42</span> <span class="nb">print</span><span class="p">(</span><span class="n">v</span><span class="p">)</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">0.2</span><span class="p">)</span> <span class="n">g</span> <span class="o">=</span> <span class="n">gen</span><span class="p">()</span> <span class="k">await</span> <span class="n">g</span><span class="o">.</span><span class="n">asend</span><span class="p">(</span><span class="kc">None</span><span class="p">)</span> <span class="c1"># Will return 42 after sleeping</span> <span class="c1"># for 0.1 seconds.</span> <span class="k">await</span> <span class="n">g</span><span class="o">.</span><span class="n">asend</span><span class="p">(</span><span class="s1">&#39;hello&#39;</span><span class="p">)</span> <span class="c1"># Will print &#39;hello&#39; and</span> <span class="c1"># raise StopAsyncIteration</span> <span class="c1"># (after sleeping for 0.2 seconds.)</span> </pre></div> </div> </li> <li><code class="docutils literal notranslate"><span class="pre">agen.athrow(typ,</span> <span class="pre">[val,</span> <span class="pre">[tb]])</span></code>: Returns an <em>awaitable</em>, that throws an exception into the <code class="docutils literal notranslate"><span class="pre">agen</span></code> generator.<p>Example:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">gen</span><span class="p">():</span> <span class="k">try</span><span class="p">:</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">0.1</span><span class="p">)</span> <span class="k">yield</span> <span class="s1">&#39;hello&#39;</span> <span class="k">except</span> <span class="ne">ZeroDivisionError</span><span class="p">:</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">0.2</span><span class="p">)</span> <span class="k">yield</span> <span class="s1">&#39;world&#39;</span> <span class="n">g</span> <span class="o">=</span> <span class="n">gen</span><span class="p">()</span> <span class="n">v</span> <span class="o">=</span> <span class="k">await</span> <span class="n">g</span><span class="o">.</span><span class="n">asend</span><span class="p">(</span><span class="kc">None</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="n">v</span><span class="p">)</span> <span class="c1"># Will print &#39;hello&#39; after</span> <span class="c1"># sleeping for 0.1 seconds.</span> <span class="n">v</span> <span class="o">=</span> <span class="k">await</span> <span class="n">g</span><span class="o">.</span><span class="n">athrow</span><span class="p">(</span><span class="ne">ZeroDivisionError</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="n">v</span><span class="p">)</span> <span class="c1"># Will print &#39;world&#39; after</span> <span class="c1"># sleeping 0.2 seconds.</span> </pre></div> </div> </li> <li><code class="docutils literal notranslate"><span class="pre">agen.aclose()</span></code>: Returns an <em>awaitable</em>, that throws a <code class="docutils literal notranslate"><span class="pre">GeneratorExit</span></code> exception into the generator. The <em>awaitable</em> can either return a yielded value, if <code class="docutils literal notranslate"><span class="pre">agen</span></code> handled the exception, or <code class="docutils literal notranslate"><span class="pre">agen</span></code> will be closed and the exception will propagate back to the caller.</li> <li><code class="docutils literal notranslate"><span class="pre">agen.__name__</span></code> and <code class="docutils literal notranslate"><span class="pre">agen.__qualname__</span></code>: readable and writable name and qualified name attributes.</li> <li><code class="docutils literal notranslate"><span class="pre">agen.ag_await</span></code>: The object that <code class="docutils literal notranslate"><span class="pre">agen</span></code> is currently <em>awaiting</em> on, or <code class="docutils literal notranslate"><span class="pre">None</span></code>. This is similar to the currently available <code class="docutils literal notranslate"><span class="pre">gi_yieldfrom</span></code> for generators and <code class="docutils literal notranslate"><span class="pre">cr_await</span></code> for coroutines.</li> <li><code class="docutils literal notranslate"><span class="pre">agen.ag_frame</span></code>, <code class="docutils literal notranslate"><span class="pre">agen.ag_running</span></code>, and <code class="docutils literal notranslate"><span class="pre">agen.ag_code</span></code>: defined in the same way as similar attributes of standard generators.</li> </ol> <p><code class="docutils literal notranslate"><span class="pre">StopIteration</span></code> and <code class="docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code> are not propagated out of asynchronous generators, and are replaced with a <code class="docutils literal notranslate"><span class="pre">RuntimeError</span></code>.</p> </section> <section id="implementation-details"> <h3><a class="toc-backref" href="#implementation-details" role="doc-backlink">Implementation Details</a></h3> <p>Asynchronous generator object (<code class="docutils literal notranslate"><span class="pre">PyAsyncGenObject</span></code>) shares the struct layout with <code class="docutils literal notranslate"><span class="pre">PyGenObject</span></code>. In addition to that, the reference implementation introduces three new objects:</p> <ol class="arabic simple"> <li><code class="docutils literal notranslate"><span class="pre">PyAsyncGenASend</span></code>: the awaitable object that implements <code class="docutils literal notranslate"><span class="pre">__anext__</span></code> and <code class="docutils literal notranslate"><span class="pre">asend()</span></code> methods.</li> <li><code class="docutils literal notranslate"><span class="pre">PyAsyncGenAThrow</span></code>: the awaitable object that implements <code class="docutils literal notranslate"><span class="pre">athrow()</span></code> and <code class="docutils literal notranslate"><span class="pre">aclose()</span></code> methods.</li> <li><code class="docutils literal notranslate"><span class="pre">_PyAsyncGenWrappedValue</span></code>: every directly yielded object from an asynchronous generator is implicitly boxed into this structure. This is how the generator implementation can separate objects that are yielded using regular iteration protocol from objects that are yielded using asynchronous iteration protocol.</li> </ol> <p><code class="docutils literal notranslate"><span class="pre">PyAsyncGenASend</span></code> and <code class="docutils literal notranslate"><span class="pre">PyAsyncGenAThrow</span></code> are awaitables (they have <code class="docutils literal notranslate"><span class="pre">__await__</span></code> methods returning <code class="docutils literal notranslate"><span class="pre">self</span></code>) and are coroutine-like objects (implementing <code class="docutils literal notranslate"><span class="pre">__iter__</span></code>, <code class="docutils literal notranslate"><span class="pre">__next__</span></code>, <code class="docutils literal notranslate"><span class="pre">send()</span></code> and <code class="docutils literal notranslate"><span class="pre">throw()</span></code> methods). Essentially, they control how asynchronous generators are iterated:</p> <a class="invert-in-dark-mode reference internal image-reference" href="../_images/pep-0525-1.png"><img alt="../_images/pep-0525-1.png" class="invert-in-dark-mode align-center" src="../_images/pep-0525-1.png" style="width: 80%;" /> </a> <section id="pyasyncgenasend-and-pyasyncgenathrow"> <h4><a class="toc-backref" href="#pyasyncgenasend-and-pyasyncgenathrow" role="doc-backlink">PyAsyncGenASend and PyAsyncGenAThrow</a></h4> <p><code class="docutils literal notranslate"><span class="pre">PyAsyncGenASend</span></code> is a coroutine-like object that drives <code class="docutils literal notranslate"><span class="pre">__anext__</span></code> and <code class="docutils literal notranslate"><span class="pre">asend()</span></code> methods and implements the asynchronous iteration protocol.</p> <p><code class="docutils literal notranslate"><span class="pre">agen.asend(val)</span></code> and <code class="docutils literal notranslate"><span class="pre">agen.__anext__()</span></code> return instances of <code class="docutils literal notranslate"><span class="pre">PyAsyncGenASend</span></code> (which hold references back to the parent <code class="docutils literal notranslate"><span class="pre">agen</span></code> object.)</p> <p>The data flow is defined as follows:</p> <ol class="arabic"> <li>When <code class="docutils literal notranslate"><span class="pre">PyAsyncGenASend.send(val)</span></code> is called for the first time, <code class="docutils literal notranslate"><span class="pre">val</span></code> is pushed to the parent <code class="docutils literal notranslate"><span class="pre">agen</span></code> object (using existing facilities of <code class="docutils literal notranslate"><span class="pre">PyGenObject</span></code>.)<p>Subsequent iterations over the <code class="docutils literal notranslate"><span class="pre">PyAsyncGenASend</span></code> objects, push <code class="docutils literal notranslate"><span class="pre">None</span></code> to <code class="docutils literal notranslate"><span class="pre">agen</span></code>.</p> <p>When a <code class="docutils literal notranslate"><span class="pre">_PyAsyncGenWrappedValue</span></code> object is yielded, it is unboxed, and a <code class="docutils literal notranslate"><span class="pre">StopIteration</span></code> exception is raised with the unwrapped value as an argument.</p> </li> <li>When <code class="docutils literal notranslate"><span class="pre">PyAsyncGenASend.throw(*exc)</span></code> is called for the first time, <code class="docutils literal notranslate"><span class="pre">*exc</span></code> is thrown into the parent <code class="docutils literal notranslate"><span class="pre">agen</span></code> object.<p>Subsequent iterations over the <code class="docutils literal notranslate"><span class="pre">PyAsyncGenASend</span></code> objects, push <code class="docutils literal notranslate"><span class="pre">None</span></code> to <code class="docutils literal notranslate"><span class="pre">agen</span></code>.</p> <p>When a <code class="docutils literal notranslate"><span class="pre">_PyAsyncGenWrappedValue</span></code> object is yielded, it is unboxed, and a <code class="docutils literal notranslate"><span class="pre">StopIteration</span></code> exception is raised with the unwrapped value as an argument.</p> </li> <li><code class="docutils literal notranslate"><span class="pre">return</span></code> statements in asynchronous generators raise <code class="docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code> exception, which is propagated through <code class="docutils literal notranslate"><span class="pre">PyAsyncGenASend.send()</span></code> and <code class="docutils literal notranslate"><span class="pre">PyAsyncGenASend.throw()</span></code> methods.</li> </ol> <p><code class="docutils literal notranslate"><span class="pre">PyAsyncGenAThrow</span></code> is very similar to <code class="docutils literal notranslate"><span class="pre">PyAsyncGenASend</span></code>. The only difference is that <code class="docutils literal notranslate"><span class="pre">PyAsyncGenAThrow.send()</span></code>, when called first time, throws an exception into the parent <code class="docutils literal notranslate"><span class="pre">agen</span></code> object (instead of pushing a value into it.)</p> </section> </section> <section id="new-standard-library-functions-and-types"> <h3><a class="toc-backref" href="#new-standard-library-functions-and-types" role="doc-backlink">New Standard Library Functions and Types</a></h3> <ol class="arabic simple"> <li><code class="docutils literal notranslate"><span class="pre">types.AsyncGeneratorType</span></code> – type of asynchronous generator object.</li> <li><code class="docutils literal notranslate"><span class="pre">sys.set_asyncgen_hooks()</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.get_asyncgen_hooks()</span></code> methods to set up asynchronous generators finalizers and iteration interceptors in event loops.</li> <li><code class="docutils literal notranslate"><span class="pre">inspect.isasyncgen()</span></code> and <code class="docutils literal notranslate"><span class="pre">inspect.isasyncgenfunction()</span></code> introspection functions.</li> <li>New method for asyncio event loop: <code class="docutils literal notranslate"><span class="pre">loop.shutdown_asyncgens()</span></code>.</li> <li>New <code class="docutils literal notranslate"><span class="pre">collections.abc.AsyncGenerator</span></code> abstract base class.</li> </ol> </section> <section id="backwards-compatibility"> <h3><a class="toc-backref" href="#backwards-compatibility" role="doc-backlink">Backwards Compatibility</a></h3> <p>The proposal is fully backwards compatible.</p> <p>In Python 3.5 it is a <code class="docutils literal notranslate"><span class="pre">SyntaxError</span></code> to define an <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code> function with a <code class="docutils literal notranslate"><span class="pre">yield</span></code> expression inside, therefore it’s safe to introduce asynchronous generators in 3.6.</p> </section> </section> <section id="performance"> <h2><a class="toc-backref" href="#performance" role="doc-backlink">Performance</a></h2> <section id="regular-generators"> <h3><a class="toc-backref" href="#regular-generators" role="doc-backlink">Regular Generators</a></h3> <p>There is no performance degradation for regular generators. The following micro benchmark runs at the same speed on CPython with and without asynchronous generators:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">gen</span><span class="p">():</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span> <span class="k">while</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">100000000</span><span class="p">:</span> <span class="k">yield</span> <span class="n">i</span> <span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span> <span class="nb">list</span><span class="p">(</span><span class="n">gen</span><span class="p">())</span> </pre></div> </div> </section> <section id="improvements-over-asynchronous-iterators"> <h3><a class="toc-backref" href="#improvements-over-asynchronous-iterators" role="doc-backlink">Improvements over asynchronous iterators</a></h3> <p>The following micro-benchmark shows that asynchronous generators are about <strong>2.3x faster</strong> than asynchronous iterators implemented in pure Python:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">N</span> <span class="o">=</span> <span class="mi">10</span> <span class="o">**</span> <span class="mi">7</span> <span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">agen</span><span class="p">():</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">N</span><span class="p">):</span> <span class="k">yield</span> <span class="n">i</span> <span class="k">class</span><span class="w"> </span><span class="nc">AIter</span><span class="p">:</span> <span class="k">def</span><span class="w"> </span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">i</span> <span class="o">=</span> <span class="mi">0</span> <span class="k">def</span><span class="w"> </span><span class="fm">__aiter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span> <span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="fm">__anext__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">i</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">i</span> <span class="k">if</span> <span class="n">i</span> <span class="o">&gt;=</span> <span class="n">N</span><span class="p">:</span> <span class="k">raise</span> <span class="ne">StopAsyncIteration</span> <span class="bp">self</span><span class="o">.</span><span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span> <span class="k">return</span> <span class="n">i</span> </pre></div> </div> </section> </section> <section id="design-considerations"> <h2><a class="toc-backref" href="#design-considerations" role="doc-backlink">Design Considerations</a></h2> <section id="aiter-and-anext-builtins"> <h3><a class="toc-backref" href="#aiter-and-anext-builtins" role="doc-backlink"><code class="docutils literal notranslate"><span class="pre">aiter()</span></code> and <code class="docutils literal notranslate"><span class="pre">anext()</span></code> builtins</a></h3> <p>Originally, <a class="pep reference internal" href="../pep-0492/" title="PEP 492 – Coroutines with async and await syntax">PEP 492</a> defined <code class="docutils literal notranslate"><span class="pre">__aiter__</span></code> as a method that should return an <em>awaitable</em> object, resulting in an asynchronous iterator.</p> <p>However, in CPython 3.5.2, <code class="docutils literal notranslate"><span class="pre">__aiter__</span></code> was redefined to return asynchronous iterators directly. To avoid breaking backwards compatibility, it was decided that Python 3.6 will support both ways: <code class="docutils literal notranslate"><span class="pre">__aiter__</span></code> can still return an <em>awaitable</em> with a <code class="docutils literal notranslate"><span class="pre">DeprecationWarning</span></code> being issued.</p> <p>Because of this dual nature of <code class="docutils literal notranslate"><span class="pre">__aiter__</span></code> in Python 3.6, we cannot add a synchronous implementation of <code class="docutils literal notranslate"><span class="pre">aiter()</span></code> built-in. Therefore, it is proposed to wait until Python 3.7.</p> </section> <section id="asynchronous-list-dict-set-comprehensions"> <h3><a class="toc-backref" href="#asynchronous-list-dict-set-comprehensions" role="doc-backlink">Asynchronous list/dict/set comprehensions</a></h3> <p>Syntax for asynchronous comprehensions is unrelated to the asynchronous generators machinery, and should be considered in a separate PEP.</p> </section> <section id="asynchronous-yield-from"> <h3><a class="toc-backref" href="#asynchronous-yield-from" role="doc-backlink">Asynchronous <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code></a></h3> <p>While it is theoretically possible to implement <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code> support for asynchronous generators, it would require a serious redesign of the generators implementation.</p> <p><code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code> is also less critical for asynchronous generators, since there is no need provide a mechanism of implementing another coroutines protocol on top of coroutines. And to compose asynchronous generators a simple <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> loop can be used:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">g1</span><span class="p">():</span> <span class="k">yield</span> <span class="mi">1</span> <span class="k">yield</span> <span class="mi">2</span> <span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">g2</span><span class="p">():</span> <span class="k">async</span> <span class="k">for</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">g1</span><span class="p">():</span> <span class="k">yield</span> <span class="n">v</span> </pre></div> </div> </section> <section id="why-the-asend-and-athrow-methods-are-necessary"> <h3><a class="toc-backref" href="#why-the-asend-and-athrow-methods-are-necessary" role="doc-backlink">Why the <code class="docutils literal notranslate"><span class="pre">asend()</span></code> and <code class="docutils literal notranslate"><span class="pre">athrow()</span></code> methods are necessary</a></h3> <p>They make it possible to implement concepts similar to <code class="docutils literal notranslate"><span class="pre">contextlib.contextmanager</span></code> using asynchronous generators. For instance, with the proposed design, it is possible to implement the following pattern:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@async_context_manager</span> <span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">ctx</span><span class="p">():</span> <span class="k">await</span> <span class="nb">open</span><span class="p">()</span> <span class="k">try</span><span class="p">:</span> <span class="k">yield</span> <span class="k">finally</span><span class="p">:</span> <span class="k">await</span> <span class="n">close</span><span class="p">()</span> <span class="k">async</span> <span class="k">with</span> <span class="n">ctx</span><span class="p">():</span> <span class="k">await</span> <span class="o">...</span> </pre></div> </div> <p>Another reason is that it is possible to push data and throw exceptions into asynchronous generators using the object returned from <code class="docutils literal notranslate"><span class="pre">__anext__</span></code> object, but it is hard to do that correctly. Adding explicit <code class="docutils literal notranslate"><span class="pre">asend()</span></code> and <code class="docutils literal notranslate"><span class="pre">athrow()</span></code> will pave a safe way to accomplish that.</p> <p>In terms of implementation, <code class="docutils literal notranslate"><span class="pre">asend()</span></code> is a slightly more generic version of <code class="docutils literal notranslate"><span class="pre">__anext__</span></code>, and <code class="docutils literal notranslate"><span class="pre">athrow()</span></code> is very similar to <code class="docutils literal notranslate"><span class="pre">aclose()</span></code>. Therefore, having these methods defined for asynchronous generators does not add any extra complexity.</p> </section> </section> <section id="example"> <h2><a class="toc-backref" href="#example" role="doc-backlink">Example</a></h2> <p>A working example with the current reference implementation (will print numbers from 0 to 9 with one second delay):</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">ticker</span><span class="p">(</span><span class="n">delay</span><span class="p">,</span> <span class="n">to</span><span class="p">):</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">to</span><span class="p">):</span> <span class="k">yield</span> <span class="n">i</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="n">delay</span><span class="p">)</span> <span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">run</span><span class="p">():</span> <span class="k">async</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">ticker</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">10</span><span class="p">):</span> <span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span> <span class="kn">import</span><span class="w"> </span><span class="nn">asyncio</span> <span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span> <span class="k">try</span><span class="p">:</span> <span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">run</span><span class="p">())</span> <span class="k">finally</span><span class="p">:</span> <span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> </pre></div> </div> </section> <section id="acceptance"> <h2><a class="toc-backref" href="#acceptance" role="doc-backlink">Acceptance</a></h2> <p><a class="pep reference internal" href="../pep-0525/" title="PEP 525 – Asynchronous Generators">PEP 525</a> was accepted by Guido, September 6, 2016 <a class="footnote-reference brackets" href="#id5" id="id1">[2]</a>.</p> </section> <section id="implementation"> <h2><a class="toc-backref" href="#implementation" role="doc-backlink">Implementation</a></h2> <p>The implementation is tracked in issue 28003 <a class="footnote-reference brackets" href="#id6" id="id2">[3]</a>. The reference implementation git repository is available at <a class="footnote-reference brackets" href="#id4" id="id3">[1]</a>.</p> </section> <section id="references"> <h2><a class="toc-backref" href="#references" role="doc-backlink">References</a></h2> <aside class="footnote-list brackets"> <aside class="footnote brackets" id="id4" role="doc-footnote"> <dt class="label" id="id4">[<a href="#id3">1</a>]</dt> <dd><a class="reference external" href="https://github.com/1st1/cpython/tree/async_gen">https://github.com/1st1/cpython/tree/async_gen</a></aside> <aside class="footnote brackets" id="id5" role="doc-footnote"> <dt class="label" id="id5">[<a href="#id1">2</a>]</dt> <dd><a class="reference external" href="https://mail.python.org/pipermail/python-dev/2016-September/146267.html">https://mail.python.org/pipermail/python-dev/2016-September/146267.html</a></aside> <aside class="footnote brackets" id="id6" role="doc-footnote"> <dt class="label" id="id6">[<a href="#id2">3</a>]</dt> <dd><a class="reference external" href="http://bugs.python.org/issue28003">http://bugs.python.org/issue28003</a></aside> </aside> </section> <section id="acknowledgments"> <h2><a class="toc-backref" href="#acknowledgments" role="doc-backlink">Acknowledgments</a></h2> <p>I thank Guido van Rossum, Victor Stinner, Elvis Pranskevichus, Nathaniel Smith, Łukasz Langa, Andrew Svetlov and many others for their feedback, code reviews, and discussions around this PEP.</p> </section> <section id="copyright"> <h2><a class="toc-backref" href="#copyright" role="doc-backlink">Copyright</a></h2> <p>This document has been placed in the public domain.</p> </section> </section> <hr class="docutils" /> <p>Source: <a class="reference external" href="https://github.com/python/peps/blob/main/peps/pep-0525.rst">https://github.com/python/peps/blob/main/peps/pep-0525.rst</a></p> <p>Last modified: <a class="reference external" href="https://github.com/python/peps/commits/main/peps/pep-0525.rst">2025-02-01 08:59:27 GMT</a></p> </article> <nav id="pep-sidebar"> <h2>Contents</h2> <ul> <li><a class="reference internal" href="#abstract">Abstract</a></li> <li><a class="reference internal" href="#rationale-and-goals">Rationale and Goals</a></li> <li><a class="reference internal" href="#specification">Specification</a><ul> <li><a class="reference internal" href="#asynchronous-generators">Asynchronous Generators</a></li> <li><a class="reference internal" href="#support-for-asynchronous-iteration-protocol">Support for Asynchronous Iteration Protocol</a></li> <li><a class="reference internal" href="#finalization">Finalization</a></li> <li><a class="reference internal" href="#asyncio">asyncio</a></li> <li><a class="reference internal" href="#asynchronous-generator-object">Asynchronous Generator Object</a></li> <li><a class="reference internal" href="#implementation-details">Implementation Details</a><ul> <li><a class="reference internal" href="#pyasyncgenasend-and-pyasyncgenathrow">PyAsyncGenASend and PyAsyncGenAThrow</a></li> </ul> </li> <li><a class="reference internal" href="#new-standard-library-functions-and-types">New Standard Library Functions and Types</a></li> <li><a class="reference internal" href="#backwards-compatibility">Backwards Compatibility</a></li> </ul> </li> <li><a class="reference internal" href="#performance">Performance</a><ul> <li><a class="reference internal" href="#regular-generators">Regular Generators</a></li> <li><a class="reference internal" href="#improvements-over-asynchronous-iterators">Improvements over asynchronous iterators</a></li> </ul> </li> <li><a class="reference internal" href="#design-considerations">Design Considerations</a><ul> <li><a class="reference internal" href="#aiter-and-anext-builtins"><code class="docutils literal notranslate"><span class="pre">aiter()</span></code> and <code class="docutils literal notranslate"><span class="pre">anext()</span></code> builtins</a></li> <li><a class="reference internal" href="#asynchronous-list-dict-set-comprehensions">Asynchronous list/dict/set comprehensions</a></li> <li><a class="reference internal" href="#asynchronous-yield-from">Asynchronous <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code></a></li> <li><a class="reference internal" href="#why-the-asend-and-athrow-methods-are-necessary">Why the <code class="docutils literal notranslate"><span class="pre">asend()</span></code> and <code class="docutils literal notranslate"><span class="pre">athrow()</span></code> methods are necessary</a></li> </ul> </li> <li><a class="reference internal" href="#example">Example</a></li> <li><a class="reference internal" href="#acceptance">Acceptance</a></li> <li><a class="reference internal" href="#implementation">Implementation</a></li> <li><a class="reference internal" href="#references">References</a></li> <li><a class="reference internal" href="#acknowledgments">Acknowledgments</a></li> <li><a class="reference internal" href="#copyright">Copyright</a></li> </ul> <br> <a id="source" href="https://github.com/python/peps/blob/main/peps/pep-0525.rst">Page Source (GitHub)</a> </nav> </section> <script src="../_static/colour_scheme.js"></script> <script src="../_static/wrap_tables.js"></script> <script src="../_static/sticky_banner.js"></script> </body> </html>

Pages: 1 2 3 4 5 6 7 8 9 10