python---協程理解

推文:python---基礎知識回顧(七)迭代器和生成器html

推文:Python協程深刻理解(本文轉載於該文章)python

從語法上來看,協程和生成器相似,都是定義體中包含yield關鍵字的函數。
yield在協程中的用法:async

  • 在協程中yield一般出如今表達式的右邊,例如:datum = yield,能夠產出值,也能夠不產出--若是yield關鍵字後面沒有表達式,那麼生成器產出None.
  • 協程可能從調用方接受數據,調用方是經過send(datum)的方式把數據提供給協程使用,而不是next(...)函數,一般調用方會把值推送給協程。
  • 協程能夠把控制器讓給中心調度程序,從而激活其餘的協程

因此整體上在協程中把yield看作是控制流程的方式。ide

協程不止能夠接受,還能夠發送

瞭解協程的過程

>>> 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(...)方式激活協程,若是不預激,這個協程就沒法使用,若是哪天在代碼中遺忘了那麼就出問題了,因此有一種預激協程的裝飾器,能夠幫助咱們幹這件事(用來幫助咱們激活協程)post

預激協程的裝飾器(自定義)

>>> 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

關於預激,在使用yield from句法調用協程的時候,會自動預激活,這樣其實與咱們上面定義的預激裝飾器是不兼容的,url

在python3.4裏面的asyncio.coroutine裝飾器不會預激協程,所以兼容yield fromspa

終止協程和異常處理(throw拋出,close終止)

協程中爲處理的異常會向上冒泡,傳給next函數或send函數的調用方(即觸發協程的對象)
拿上面的代碼舉例子,若是咱們發送了一個字符串而不是一個整數的時候就會報錯,而且這個時候協程是被終止了code

>>> 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 >>> averager.send('z')  #咱們應該對異常進行處理 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 8, in averager TypeError: unsupported operand type(s) for +=: 'float' and 'str'

異常處理

class TestException(Exception):
    '''自定義異常'''


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:
            try:
                term = yield aver
            except TestException:
                print('捕獲到TestException')
                term = 0
                count -= 1

            total += term
            count += 1
            aver = total/count
coro_avg = averager()
print(coro_avg.send(10))
print(coro_avg.send(20))
print(coro_avg.send(30))
print(coro_avg.throw(TestException))
print(coro_avg.send('z'))  #報錯TypeError,未捕獲
averager.close()

讓協程返回值

經過下面的例子進行演示如何獲取協程的返回值:

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
            if term is None:
                break

            total += term
            count += 1
            aver = total/count
    return 101

coro_avg = averager()
print(coro_avg.send(10))
print(coro_avg.send(20))
print(coro_avg.send(30))
try:  #獲取咱們的返回值 coro_avg.send(None) except StopIteration as e: print(e.value) averager.close()

如果不去捕獲異常:orm

StopIteration: 101  #拋出咱們要獲取的值

其實相對來講上面這種方式獲取返回值比較麻煩,而yield from 結構會自動捕獲StopIteration異常,

這種處理方式與for循環處理StopIteration異常的方式同樣,循環機制使咱們更容易理解處理異常,

對於yield from來講,解釋器不只會捕獲StopIteration異常,還會把value屬性的值變成yield from表達式的值

關於yield from(重點)

生成器gen中使用yield from subgen()時,subgen會得到控制權,把產出的值傳給gen的調用方,即調用方能夠直接控制subgen,

同時,gen會阻塞,等待subgen終止

yield from x表達式對x對象所作的第一件事是,調用iter(x),從中獲取迭代器,所以x能夠是任何可迭代的對象

yield from能夠簡化yield表達式

def genyield():
    for c in "AB":
        yield c

    for i in range(1,3):
        yield i

print(list(genyield()))

def genyieldfrom():
    yield from "AB"
    yield from range(1,3)

print(list(genyieldfrom()))

這兩種的方式的結果是同樣的,可是這樣看來yield from更加簡潔,可是yield from的做用可不單單是替代產出值的嵌套for循環。
yield from的主要功能是打開雙向通道,把最外層的調用方與最內層的子生成器鏈接起來,這樣兩者能夠直接發送和產出值,還能夠直接傳入異常,而不用再像以前那樣在位於中間的協程中添加大量處理異常的代碼

對StopIteration和return進行簡化

委派生成器在yield from 表達式處暫停時,調用方能夠直接把數據發給子生成器,子生成器再把產出產出值發給調用方,子生成器返回以後,解釋器會拋出StopIteration異常,並把返回值附加到異常對象上,此時委派生成器會恢復。

 

from collections import namedtuple


Result = namedtuple('Result', 'count average')


# 子生成器
def averager():
    total = 0.0
    count = 0
    average = None
    while True:
        term = yield
        if term is None:
            break
        total += term
        count += 1
        average = total/count
    return Result(count, average)


# 委派生成器
def grouper(result, key):
    while True:
        # print(key)    #能夠知道,對於每一組數據,都是經過委派生成器傳遞的,開始傳遞一次,結束獲取結果的時候又傳遞一次
        result[key] = yield from averager() #將返回結果收集


# 客戶端代碼,即調用方
def main(data):
    results = {}
    for key,values in data.items():
        group = grouper(results,key)
        next(group)
        for value in values:
            group.send(value)
        group.send(None) #這裏表示要終止了

    report(results)


# 輸出報告
def report(results):
    for key, result in sorted(results.items()):
        group, unit = key.split(';')
        print('{:2} {:5} averaging {:.2f}{}'.format(
            result.count, group, result.average, unit
        ))

data = {
    'girls;kg':
        [40.9, 38.5, 44.3, 42.2, 45.2, 41.7, 44.5, 38.0, 40.6, 44.5],
    'girls;m':
        [1.6, 1.51, 1.4, 1.3, 1.41, 1.39, 1.33, 1.46, 1.45, 1.43],
    'boys;kg':
        [39.0, 40.8, 43.2, 40.8, 43.1, 38.6, 41.4, 40.6, 36.3],
    'boys;m':
        [1.38, 1.5, 1.32, 1.25, 1.37, 1.48, 1.25, 1.49, 1.46],
}


if __name__ == '__main__':
    main(data)

關於上述代碼着重解釋一下關於委派生成器部分,這裏的循環每次迭代時會新建一個averager實例,每一個實例都是做爲協程使用的生成器對象。

grouper發送的每一個值都會經由yield from處理,經過管道傳給averager實例。grouper會在yield from表達式處暫停,等待averager實例處理客戶端發來的值。averager實例運行完畢後,返回的值會綁定到results[key]上,while 循環會不斷建立averager實例,處理更多的值

而且上述代碼中的子生成器能夠使用return 返回一個值,而返回的值會成爲yield from表達式的值。

是一組數據一組數據按照順序處理的。

關於yield from的意義

關於yield from 六點重要的說明:

  1. 子生成器產出的值都直接傳給委派生成器的調用方(即客戶端代碼)
  2. 使用send()方法發送給委派生成器的值都直接傳給子生成器。若是發送的值爲None,那麼會給委派調用子生成器的__next__()方法。若是發送的值不是None,那麼會調用子生成器的send方法,若是調用的方法拋出StopIteration異常,那麼委派生成器恢復運行,任何其餘異常都會向上冒泡,傳給委派生成器
  3. 生成器退出時,生成器(或子生成器)中的return expr表達式會出發StopIteration(expr)異常拋出
  4. yield from表達式的值是子生成器終止時傳給StopIteration異常的第一個參數。yield from 結構的另外兩個特性與異常和終止有關。
  5. 傳入委派生成器的異常,除了GeneratorExit以外都傳給子生成器的throw()方法。若是調用throw()方法時拋出StopIteration異常,委派生成器恢復運行。StopIteration以外的異常會向上冒泡,傳給委派生成器
  6. 若是把GeneratorExit異常傳入委派生成器,或者在委派生成器上調用close()方法,那麼在子生成器上調用clsoe()方法,若是它有的話。若是調用close()方法致使異常拋出,那麼異常會向上冒泡,傳給委派生成器,不然委派生成器拋出GeneratorExit異常
相關文章
相關標籤/搜索