对于yield from目前我只知道这一种用法,我对它的理解也停留在yield from generator
In [1]: def reader():
...: """A generator that fakes a read from a file, socket, etc."""
...: for i in range(4):
...: yield '<< %s' % i
...:
In [2]: def reader_wrapper(g):
...: yield from g
...:
In [3]: wrap = reader_wrapper(reader())
In [4]: for i in wrap:
...: print(i)
...:
<< 0
<< 1
<< 2
<< 3
但是在廖雪峰的异步IO教程中看见一个yield from的新用法,请问下面这个yield from asyncio.sleep(1)是什么意思,asyncio.sleep(1)也是一个生成器吗?看官方文档也没有给出明确的解释,也是直接贴的代码,拜托大神解释一下!
import asyncio
@asyncio.coroutine
def hello():
print("Hello world!")
# 异步调用asyncio.sleep(1):
r = yield from asyncio.sleep(1)
print("Hello again!")
# 获取EventLoop:
loop = asyncio.get_event_loop()
# 执行coroutine
loop.run_until_complete(hello())
loop.close()
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
协程的本质就是是生成器
可以看看这个视频~
探索 Python 3.5 中 async/await 特性的实现
为什么要包装一次了?
这样也能用啊?很纳闷。。。
可以看看 Python 作者写的这篇文章,糙译