Text of peps.python.org › pep-0492 as Styx crawled it on Nov 19, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

PEP 492 – Coroutines with async and await syntax | peps.python.org

PEP 492 – Coroutines with async and await syntax PEP 492 – Coroutines with async and await syntax Author : Yury Selivanov <yury at edgedb.com> Discussions-To : Python-Dev list Status : Final Type : Standards Track Created : 09-Apr-2015 Python-Version : 3.5 Post-History : 17-Apr-2015, 21-Apr-2015, 27-Apr-2015, 29-Apr-2015, 05-May-2015 Table of Contents Abstract API Design and Implementation Revisions Rationale and Goals Specification New Coroutine Declaration Syntax types.coroutine() Await Expression Updated operator precedence table Examples of “await” expressions Asynchronous Context Managers and “async with” New Syntax Example Asynchronous Iterators and “async for” New Syntax Example 1 Example 2 Why StopAsyncIteration?

Coroutine objects Differences from generators Coroutine object methods Debugging Features New Standard Library Functions New Abstract Base Classes Glossary Transition Plan Backwards Compatibility asyncio asyncio migration strategy async/await in CPython code base Grammar Updates Deprecation Plans Design Considerations PEP 3152 Coroutine-generators Why “async” and “await” keywords Why “__aiter__” does not return an awaitable Importance of “async” keyword Why “async def” Why not “await for” and “await with” Why “async def” and not “def async” Why not a __future__ import Why magic methods start with “a” Why not reuse existing magic names Why not reuse existing “for” and “with” statements Comprehensions Async lambda functions Performance Overall Impact Tokenizer modifications async/await Reference Implementation List of high-level changes and new protocols Working example Acceptance Implementation References Acknowledgments Copyright Abstract The growth of Internet and general connectivity has triggered the proportionate need for responsive and scalable code.

This proposal aims to answer that need by making writing explicitly asynchronous, concurrent Python code easier and more Pythonic. It is proposed to make coroutines a proper standalone concept in Python, and introduce new supporting syntax. The ultimate goal is to help establish a common, easily approachable, mental model of asynchronous programming in Python and make it as close to synchronous programming as possible.

This PEP assumes that the asynchronous tasks are scheduled and coordinated by an Event Loop similar to that of stdlib module asyncio.events.AbstractEventLoop . While the PEP is not tied to any specific Event Loop implementation, it is relevant only to the kind of coroutine that uses yield as a signal to the scheduler, indicating that the coroutine will be waiting until an event (such as IO) is completed. We believe that the changes proposed here will help keep Python relevant and competitive in a quickly growing area of asynchronous programming, as many other languages have adopted, or are planning to adopt, similar features: [2] , [5] , [6] , [7] , [8] , [10] .

API Design and Implementation Revisions Feedback on the initial beta release of Python 3.5 resulted in a redesign of the object model supporting this PEP to more clearly separate native coroutines from generators - rather than being a new kind of generator, native coroutines are now their own completely distinct type (implemented in [17] ). This change was implemented based primarily due to problems encountered attempting to integrate support for native coroutines into the Tornado web server (reported in [18] ).

In CPython 3.5.2, the __aiter__ protocol was updated. Before 3.5.2, __aiter__ was expected to return an awaitable resolving to an asynchronous iterator . Starting with 3.5.2, __aiter__ should return asynchronous iterators directly. If the old protocol is used in 3.5.2, Python will raise a PendingDeprecationWarning . In CPython 3.6, the old __aiter__ protocol will still be supported with a DeprecationWarning being raised.

In CPython 3.7, the old __aiter__ protocol will no longer be supported: a RuntimeError will be raised if __aiter__ returns anything but an asynchronous iterator. See [19] and [20] for more details. Rationale and Goals Current Python supports implementing coroutines via generators (PEP 342), further enhanced by the yield from syntax introduced in PEP 380. This approach has a number of shortcomings: It is easy to confuse coroutines with regular generators, since they share the same syntax; this is especially true for new developers.

Whether or not a function is a coroutine is determined by a presence of yield or yield from statements in its body , which can lead to unobvious errors when such statements appear in or disappear from function body during refactoring. Support for asynchronous calls is limited to expressions where yield is allowed syntactically, limiting the usefulness of syntactic features, such as with and for statements. This proposal makes coroutines a native Python language feature, and clearly separates them from generators.

This removes generator/coroutine ambiguity, and makes it possible to reliably define coroutines without reliance on a specific library. This also enables linters and IDEs to improve static code analysis and refactoring. Native coroutines and the associated new syntax features make it possible to define context manager and iteration protocols in asynchronous terms. As shown later in this proposal, the new async with statement lets Python programs perform asynchronous calls when entering and exiting a runtime context, and the new async for statement makes it possible to perform asynchronous calls in iterators.

Specification This proposal introduces new syntax and semantics to enhance coroutine support in Python. This specification presumes knowledge of the implementation of coroutines in Python ( PEP 342 and PEP 380 ). Motivation for the syntax changes proposed here comes from the asyncio framework ( PEP 3156 ) and the “Cofunctions” proposal ( PEP 3152 , now rejected in favor of this specification). From this point in this document we use the word native coroutine to refer to functions declared using the new syntax. generator-based coroutine is used where necessary to refer to coroutines that are based on generator syntax. coroutine is used in contexts where both definitions are applicable.

New Coroutine Declaration Syntax The following new syntax is used to declare a native coroutine : async def read_data ( db ): pass Key properties of coroutines : async def functions are always coroutines, even if they do not contain await expressions. It is a SyntaxError to have yield or yield from expressions in an async function. Internally, two new code object flags were introduced: CO_COROUTINE is used to mark native coroutines (defined with new syntax).

CO_ITERABLE_COROUTINE is used to make generator-based coroutines compatible with native coroutines (set by types.coroutine() function). Regular generators, when called, return a generator object ; similarly, coroutines return a coroutine object. StopIteration exceptions are not propagated out of coroutines, and are replaced with a RuntimeError . For regular generators such behavior requires a future import (see PEP 479 ).

When a native coroutine is garbage collected, a RuntimeWarning is raised if it was never awaited on (see also Debugging Features ). See also Coroutine objects section. types.coroutine() A new function coroutine(fn) is added to the types module. It allows interoperability between existing generator-based coroutines in asyncio and native coroutines introduced by this PEP: @types . coroutine def process_data ( db ): data = yield from read_data ( db ) ...

The function applies CO_ITERABLE_COROUTINE flag to generator-function’s code object, making it return a coroutine object. If fn is not a generator function , it is wrapped. If it returns a generator , it will be wrapped in an awaitable proxy object (see below the definition of awaitable objects). Note, that the CO_COROUTINE flag is not applied by types.coroutine() to make it p

The rest of this page is on the live site.