能在 await 表达式中使用的对象。可以是 coroutine 或是具有 __await__()
方法的对象。参见 PEP 492。
注意可等待对象有两种:
coroutine
,在上节中有讲;- 具有
__await__()
方法的对象,只要一个类实现了__await__方法
,那么通过它构造出来的实例就是一个Awaitable
。
下面这段代码就是 awaitable 抽象基类:
class Awaitable(metaclass=ABCMeta):
__slots__ = ()
@abstractmethod
def __await__(self): # 必须返回一个 iterator
yield
@classmethod
def __subclasshook__(cls, C):
if cls is Awaitable:
return _check_methods(C, "__await__")
return NotImplemented
用 async def
复合语句创建的函数,它返回的是一个Coroutine对象,而刚好Coroutine继承于Awaitable
在 asyncio
包中有个函数,接受一个 awaitable
, 通过 yield from awaitable.__await__()
来代理访问可等待对象的 __await__
方法返回的可迭代对象。
# asyncio.tasks.py
@coroutine
def _wrap_awaitable(awaitable):
"""Helper for asyncio.ensure_future().
Wraps awaitable (an object with __await__) into a coroutine
that will later be wrapped in a Task by ensure_future().
"""
return (yield from awaitable.__await__())