__await__返回迭代器,因为协程的底层机制最初基于yield from语法。实际上,__await__返回iter(some_future)或{}。它可用于创建每次等待时产生不同值的对象。请看这个简单的例子:import asyncio
import random
class RandomProducer:
def __await__(self):
return self.producer().__await__()
async def producer(self):
sleep = random.random()
value = random.randint(0, 9)
return await asyncio.sleep(sleep, result=value)
async def main():
producer = RandomProducer()
while True:
print(await producer)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
回答您的意见:Does every coroutine eventually ends up calling asyncio.sleep?
不,而且asyncio.sleep实际上不是链的末端。在最底层,它总是一个正在被让渡的未来:协程链请求事件循环“当这个未来有结果时请叫醒我”。在asyncio.sleep的情况下,它使用loop.call_later设置给定时间后的未来结果。循环为调度回调提供了更多的方法:loop.call_at,loop.add_reader,loop.add_writer,loop.add_signal_handler,等等An asyncio library such as aiohttp. I'm assuming there is some code somewhere that doesn't rely on existence of previous coroutines.
为了实现单线程并发,所有的IO操作都必须委托给事件循环。
例如,aiohttp依赖于loop.create_connection协程到manage the TCP connection。在