Python Coroutine Function
A coroutine function object is a block of compound statements defined by a Python coroutine definiton.
Coroutine Function Definitions
A coroutine function definition is defined as
async_funcdef::=[decorators] "async" "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite
Features of Coroutine Function Definition
Execution of Python coroutines can be suspended and resumed at many points (see coroutine). Inside the body of a coroutine function, await and async identifiers become reserved keywords; await expressions, async for and async with can only be used in coroutine function bodies.
Functions defined with async def syntax are always coroutine functions, even if they do not contain await or async keywords.
It is a SyntaxError to use a yield from expression inside the body of a coroutine function.
An example of a coroutine function:
async def func(param1, param2):
do_stuff()
await some_coroutine()
8.8.2. The async for statement
async_for_stmt ::= "async" for_stmt
An asynchronous iterable is able to call asynchronous code in its iter implementation, and asynchronous iterator can call asynchronous code in its next method.
The async for statement allows convenient iteration over asynchronous iterators.
The following code:
async for TARGET in ITER:
SUITE
else:
SUITE2
Is semantically equivalent to:
iter = (ITER)
iter = type(iter).__aiter__(iter)
running = True
while running:
try:
TARGET = await type(iter).__anext__(iter)
except StopAsyncIteration:
running = False
else:
SUITE
else:
SUITE2
See also __aiter__() and __anext__() for details.
It is a SyntaxError to use an async for statement outside the body of a coroutine function.
8.8.3. The async with statement
async_with_stmt ::= "async" with_stmt
An asynchronous context manager is a context manager that is able to suspend execution in its enter and exit methods.
The following code:
async with EXPRESSION as TARGET:
SUITE
is semantically equivalent to:
manager = (EXPRESSION)
aexit = type(manager).__aexit__
aenter = type(manager).__aenter__
value = await aenter(manager)
hit_except = False
try:
TARGET = value
SUITE
except:
hit_except = True
if not await aexit(manager, *sys.exc_info()):
raise
finally:
if not hit_except:
await aexit(manager, None, None, None)
See also __aenter__() and __aexit__() for details.
It is a SyntaxError to use an async with statement outside the body of a coroutine function.
See also
PEP 492 - Coroutines with async and await syntax
The proposal that made coroutines a proper standalone concept in Python, and added supporting syntax.
Source and Reference