CKTIS / Python
Keyword async
An async def without yield creates a coroutine function whose call returns a coroutine object without executing the body.
Version: Python 3.14; repository image, production runtime not attested
Syntax
async def read(source, manager):
async with manager:
async for item in source:
...An async def without yield creates a coroutine function whose call returns a coroutine object without executing the body.
Adding yield creates an asynchronous generator function whose call returns an asynchronous generator object. In ordinary modules async for and async with are restricted to the body of an async def, handling asynchronous iteration or context entry and exit.
Async syntax alone does not start tasks in parallel.
Examples
import asyncio
from contextlib import nullcontext
async def rows():
yield 2
yield 5
async def collect(trace):
trace.append("started")
async with nullcontext("ok") as label:
assert label == "ok"
return [v async for v in rows()]
trace = []
job = collect(trace)
print(trace)
print(asyncio.run(job), trace)
import inspect
assert inspect.isasyncgenfunction(rows) and inspect.isasyncgen(rows())
for source in ("async for x in y:\n pass", "async with m:\n pass"):
try:
compile(source, "<module>", "exec")
except SyntaxError:
continue
raise AssertionError(source)
Result
[] [2, 5] ['started']
Async syntax alone does not start tasks in parallel.