【发布时间】:2018-10-14 09:34:11
【问题描述】:
考虑这个简单的协程
In [9]: async def coro():
...: print('hello world')
...:
我们知道原生协程不是迭代器
In [12]: type(c)
Out[12]: coroutine
In [13]: next(c)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-e846efec376d> in <module>()
----> 1 next(c)
TypeError: 'coroutine' object is not an iterator
但是,如果我运行协程,我会收到 StopIteration 错误。
In [10]: c = coro()
In [11]: c.send(None)
hello world
---------------------------
StopIteration Traceback (most recent call last)
<ipython-input-11-d9162d5dda48> in <module>()
----> 1 c.send(None)
StopIteration:
this 回答原生协程在功能上等同于基于生成的协程。但同一问题的另一个答案更进一步,并解释了它们如何服务于不同的目的。
本机 coros 引发 StopIteration 错误的唯一原因是它们与基于生成器的 coros 共享重要代码吗?还是还有其他原因?
【问题讨论】:
标签: python asynchronous