coroutines总结整理
2018-01-07 本文已影响71人
ThomasYoungK
这次看了一些关于协程(coroutine)的资料,这是python特有的,我会在这篇文字里面慢慢总结整理下来,估计会写个1周多。
coroutine和generator的关系
generator用到了yield语法,而coroutine也是用到了yield语法,什么区别呢?大致是这样的:
- generator是为iteration产生数据
- coroutine是消费数据
- coroutine也可以产生值,但目的不是为了迭代
- 不要把2个概念混在一起,写出让大家摸不着头脑的代码
下面的代码是generator,用来倒数迭代用
# countdown.py
#
# A simple generator function
def countdown(n):
print "Counting down from", n
while n > 0:
yield n
n -= 1
print "Done counting down"
# Example use
if __name__ == '__main__':
for i in countdown(5):
print i
输出是
Counting down from 5
5
4
3
2
1
Done counting down
下面代码是coroutine,用来消费字符串,过滤出有用的行
# grep.py
#
# A very simple coroutine
def grep(pattern):
print "Looking for %s" % pattern
while True:
line = (yield)
if pattern in line:
print line,
# Example use
if __name__ == '__main__':
g = grep("python")
# g.send(None)
g.next()
g.send("Yeah, but no, but yeah, but no")
g.send("A series of tubes")
g.send("python generators rock!")
g.close()
输出是
Looking for python
python generators rock!
千万不要写下面的代码,又想消费,又想迭代,结果不知所云:
# bogus.py
#
# Bogus example of a generator that produces and receives values
def countdown(n):
print "Counting down from", n
while n >= 0:
newvalue = (yield n)
# If a new value got sent in, reset n with it
if newvalue is not None:
n = newvalue
else:
n -= 1
# The holy grail countdown
c = countdown(5)
for x in c:
print x
if x == 5:
c.send(3)
输出是:
Counting down from 5
5
2
1
0