1. 程式人生 > >python---協程理解

python---協程理解

技術分享 sync type get 其他 value 一次 並且 star

推文: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:執行結束
>>> 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

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

在python3.4裏面的asyncio.coroutine裝飾器不會預激協程,因此兼容yield from

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

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

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

若是不去捕獲異常:

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

python---協程理解