Coroutine functions
Define non-blocking operations that can pause while awaiting I/O or another awaitable.
Python · Const
async is Python’s syntax family for coroutine functions and asynchronous control flow. It introduces async def, async for, and async with; await is used within coroutine bodies to suspend execution until an awaitable completes.
Python uses async syntax to define coroutine functions and asynchronous control-flow statements. Calling an async def function produces a coroutine; await suspends the current coroutine until an awaitable completes, while async for and async with provide asynchronous iteration and resource management inside coroutine functions.
async def funcname([parameter_list]) [-> expression]: suite
async for_stmt
async with EXPRESSION as TARGET: SUITEimport asyncio
async def fetch_value():
await asyncio.sleep(0)
return 42
async def main():
value = await fetch_value()
print(value)
asyncio.run(main())Defines a coroutine with async def, suspends it with await, and runs it from a synchronous entry point.
Define non-blocking operations that can pause while awaiting I/O or another awaitable.
Consume data from an asynchronous source as items become available.
Manage resources whose enter and exit operations are asynchronous.
async def declares a coroutine function. Calling it returns a coroutine object, and the coroutine executes when it is awaited or otherwise scheduled by an event loop.
Follow-up: Can async def omit await? Yes. The documentation states that async def functions remain coroutine functions even without await or another async keyword.
await can appear only in a coroutine function body. It suspends the executing coroutine at an awaitable operation so other asynchronous work can proceed.
Follow-up: Where else is async syntax used? async for iterates asynchronous iterables, and async with manages asynchronous context managers.
async for is the asynchronous counterpart of for: it works with an asynchronous iterable whose __aiter__ method supplies an asynchronous iterator. async with is the asynchronous counterpart of with and is restricted to coroutine bodies.
Follow-up: What does an asynchronous iterable provide? It provides __aiter__, which directly returns an asynchronous iterator capable of calling asynchronous code in __anext__.
awaitasync defasync forasync withcoroutineasynchronous iterableasynchronous iterator