13.3. AsyncIO Awaitable¶
Since Python 3.5 PEP 492 -- Coroutines with async and await syntax
Object is an awaitable if it can be used in an
await
expressionAwaitable objects: Coroutines, Tasks, Futures
__await__
andawait
keyword
- aw¶
- awaitable¶
Object is an awaitable if it can be used in an
await
expression- aws¶
Awaitables
- coroutine¶
Coroutine - a function which can run concurrently.
- tasks¶
Runs thing in the "background". Can be awaited and cancelled.
- future¶
An awaitable object generally implements an __await__()
method.
Coroutine objects returned from async def functions are awaitable. Note
The generator iterator objects returned from generators decorated with
types.coroutine()
or asyncio.coroutine()
are also awaitable, but
they do not implement __await__()
.
object.__await__(self)
Must return an iterator. Should be used to
implement awaitable objects. For instance, asyncio.Future
implements
this method to be compatible with the await expression.
[2]
13.3.1. Awaitables¶
There are three main types of awaitable objects:
Coroutines,
Tasks,
Futures.
Coroutines are a low level concept and doesn't know about asyncio concepts such as EventLoop and Cancellations.
Tasks wraps around a coroutine object and allows for handling exceptions, gathering results etc.
13.3.2. Objects¶
Features of Python:
>>> from collections.abc import Awaitable
>>> from collections.abc import Coroutine
Features of AsyncIO library:
>>> from asyncio import Future
>>> from asyncio import Task

Figure 13.14. Source: Langa, Ł. import asyncio: Learn Python's AsyncIO [1]¶
13.3.3. Typing¶
>>> from collections.abc import Awaitable
>>> from collections.abc import Coroutine
>>> from collections.abc import AsyncIterable
>>> from collections.abc import AsyncIterator
>>> from collections.abc import AsyncGenerator