推文:python---基础知识回顾(七)迭代器和生成器

推文:Python协程深入理解(本文转载于该文章)

从语法上来看,协程和生成器类似,都是定义体中包含yield关键字的函数。
yield在协程中的用法:

  • 在协程中yield通常出现在表达式的右边,例如:datum = yield,可以产出值,也可以不产出--如果yield关键字后面没有表达式,那么生成器产出None.
  • 协程可能从调用方接受数据,调用方是通过send(datum)的方式把数据提供给协程使用,而不是next(...)函数,通常调用方会把值推送给协程。
  • 协程可以把控制器让给中心调度程序,从而激活其他的协程

所以总体上在协程中把yield看做是控制流程的方式。

协程不止可以接受,还可以发送

>>> def simple_corotine():
...     print('---->coroutine started')
...     x = yield  #有接收值,所以同生成器一样,需要先激活,使用next
...     print('---->coroutine recvied:',x)
...
>>> my_coro = simple_corotine()
>>> my_coro
<generator object simple_corotine at 0x0000000000A8A518>
>>> next(my_coro)  #先激活生成器,执行到yield val语句  #或者使用send(None)也可以激活生成器
---->coroutine started
>>> my_coro.send(24)  #向其中传入值,x = yield
---->coroutine recvied: 24
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration  #当生成器执行完毕时会报错

若是我们没有激活生成器,会报错

>>> def simple_corotine():
...     print('---->coroutine started')
...     x = yield
...     print('---->coroutine recvied:',x)
...
>>> my_coro = simple_corotine()
>>> my_coro
<generator object simple_corotine at 0x0000000000A8A518>
>>> my_coro.send(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't send non-None value to a just-started generator

协程在运行中的四种状态

GEN_CREATE:等待开始执行
GEN_RUNNING:解释器正在执行,这个状态一般看不到
GEN_SUSPENDED:在yield表达式处暂停
GEN_CLOSED:执行结束  
>>> from inspect import getgeneratorstate  #状态查看需要引入

>>> def simple_corotine(val): ... print('---->coroutine started: val=',val) ... b = yield val ... print('---->coroutine received: b=',b) ... c = yield val + b ... print('---->coroutine received: c=',c) ... >>> my_coro = simple_corotine(12) >>> from inspect import getgeneratorstate >>> getgeneratorstate(my_coro) 'GEN_CREATED'  #创建未激活 >>> my_coro.send(None) ---->coroutine started: val= 12 12 >>> getgeneratorstate(my_coro) 'GEN_SUSPENDED'  #在yield处暂停 >>> my_coro.send(13) ---->coroutine received: b= 13 25 >>> getgeneratorstate(my_coro) 'GEN_SUSPENDED' >>> my_coro.send(14) ---->coroutine received: c= 14 Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>> getgeneratorstate(my_coro) 'GEN_CLOSED'  #执行结束 >>>

再使用一个循环例子来了解协程:求平均值

>>> def averager():
...     total = 0.0
...     count = 0
...     aver = None
...     while True:
...             term = yield aver
...             total += term
...             count += 1
...             aver = total/count
...
>>> coro_avg = averager()
>>> coro_avg.send(None)
>>> coro_avg.send(10)
10.0
>>> coro_avg.send(20)
15.0
>>> coro_avg.send(30)
20.0
>>> coro_avg.send(40)
25.0

这里是一个死循环,只要不停send值给协程,可以一直计算下去。
通过上面的几个例子我们发现,我们如果想要开始使用协程的时候必须通过next(...)方式激活协程,如果不预激,这个协程就无法使用,如果哪天在代码中遗忘了那么就出问题了,所以有一种预激协程的装饰器,可以帮助我们干这件事(用来帮助我们激活协程)

预激协程的装饰器(自定义)

>>> def coro_active(func):
...     def inner(*args,**kwargs):
...         gen = func(*args,**kwargs)
...         next(gen)   #gen.send(None)
...         return gen
...     return inner
...
>>> @coro_active
... def averager():
...     total = 0.0
...     count = 0
...     aver = None
...     while True:
...             term = yield aver
...             total += term
...             count += 1
...             aver = total/count
...
>>> coro_avg = averager()
>>> coro_avg.send(10) 10.0 
>>> coro_avg.send(20) 15.0
>>> coro_avg.send(30) 20.0
def coro_active(func):
    def inner(*args,**kwargs):
        gen = func(*args,**kwargs)
        next(gen)   #gen.send(None)
        return gen
    return inner

@coro_active
def averager():
    total = 0.0
    count = 0
    aver = None
    while True:
            term = yield aver
            total += term
            count += 1
            aver = total/count
View Code

相关文章: