about 3 years ago

Consider Coroutines to Run Many Functions Concurrently

這個條款在講 coroutines ,簡單來說就是 generator 只不過可以透過 send() 傳值。

要注意的是必須先執行 next(generator) ,這個動作叫做 coroutine priming。每次這樣做有點麻煩,所以很多時候是做成 decorator 以方便使用。

import functools

def coroutine(function):
    @functools.wraps(function)
    def prime(*args, **kwargs):
        generator = function(*args, **kwargs)
        next(generator)
        return generator
    return prime

@coroutine
def minimize():
    current = yield
    while True:
        value = yield current
        current = min(value, current)

it = minimize()
print(it.send(10))
print(it.send(4))
print(it.send(22))
print(it.send(-1))

當然不一定要用無窮迴圈,Python 3 可以在凾式中返回。

def delegated():
    yield 1
    return 2
    yield 'Not reached'

def composed():
    try:
        for value in delegated():
            yield value
    except StopIteration as e:
        output = e.value
    yield output * 4

print list(composed())

Python 2 的話要自己弄個 exception 來回傳結果。

class MyReturn(Exception):
    def __init__(self, value):
        self.value = value

def delegated():
    yield 1
    raise MyReturn(2)
    yield 'Not reached'

def composed():
    try:
        for value in delegated():
            yield value
    except MyReturn as e:
        output = e.value
    yield output * 4
← Effective Python 心得筆記: Item 39 Effective Python 心得筆記: Item 41 →
 
comments powered by Disqus