CKTIS / Python
Schlüsselwort async
Eine async-def-Definition ohne yield erzeugt eine Koroutinenfunktion, deren Aufruf ein Koroutinenobjekt liefert, ohne den Rumpf auszuführen.
Version: Python 3.14; repository image, production runtime not attested
Syntax
async def read(source, manager):
async with manager:
async for item in source:
...Eine async-def-Definition ohne yield erzeugt eine Koroutinenfunktion, deren Aufruf ein Koroutinenobjekt liefert, ohne den Rumpf auszuführen.
Mit yield entsteht eine asynchrone Generatorfunktion, deren Aufruf erst das asynchrone Generatorobjekt liefert. In normalen Modulen stehen async for und async with im Rumpf einer async def und steuern asynchrone Iteration beziehungsweise Kontexteintritt und -austritt.
Die Syntax allein startet keine parallelen Aufgaben.
Beispiele
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)
Ergebnis
[] [2, 5] ['started']
Die Syntax allein startet keine parallelen Aufgaben.