Coroutine Syntax
suggest changeDefine native coroutines with async def and suspend them with await. Use asyncio.run() as the top-level entry point:
import asyncio
async def message_after(delay, message):
await asyncio.sleep(delay)
return message
async def main():
message = await message_after(0.1, "Hello, world!")
print(message)
asyncio.run(main())
Use asyncio.gather() to run several awaitables concurrently and retain their result order. This second program expects message_after from the example above:
async def main():
first, second = await asyncio.gather(
message_after(0.2, "first"),
message_after(0.1, "second"),
)
print(first, second)
asyncio.run(main())
Generator-based coroutines that use @asyncio.coroutine and yield from were removed in Python 3.11. Use native coroutines.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents