coroutine - python yield协程 - "产量 "这个关键词有什么作用?

python yield多个值 / python / iterator / generator / yield

Python中 yield 关键字的用途是什么?

例如,我试图理解这段代码1

def _get_child_candidates(self, distance, min_dist, max_dist):
    if self._leftchild and distance - max_dist < self._median:
        yield self._leftchild
    if self._rightchild and distance + max_dist >= self._median:
        yield self._rightchild  

这是来电者。

result, candidates = [], [self]
while candidates:
    node = candidates.pop()
    distance = node._get_dist(obj)
    if distance <= max_dist and distance >= min_dist:
        result.extend(node._values)
    candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result

iliketocode



Answer #1
>>> def func():
...     yield 'I am'
...     yield 'a generator!'
... 
>>> type(func)                 #具有yield的函数仍然是一个函数
<type 'function'>
>>> gen = func()
>>> type(gen)                  #但它返回一个生成器
<type 'generator'>
>>> hasattr(gen, '__iter__')   #这是一个迭代
True
>>> hasattr(gen, 'next')       #和.next(在Python 3中为.__ next__)
True                           # implements the iterator protocol.

生成器类型是迭代器的一个子类型。

>>> import collections, types
>>> issubclass(types.GeneratorType, collections.Iterator)
True

如果有必要,我们可以这样打字检查。

>>> isinstance(gen, types.GeneratorType)
True
>>> isinstance(gen, collections.Iterator)
True
>>> list(gen)
['I am', 'a generator!']
>>> list(gen)
[]

如果你想再次使用它的功能,你必须再做一个(见脚注2)。

>>> list(func())
['I am', 'a generator!']

比如说,可以通过程序化的方式产生数据。

def func(an_iterable):
    for item in an_iterable:
        yield item
def func(an_iterable):
    yield from an_iterable
def bank_account(deposited, interest_rate):
    while True:
        calculated_interest = interest_rate * deposited 
        received = yield calculated_interest
        if received:
            deposited += received


>>> my_account = bank_account(1000, .05)
>>> first_year_interest = next(my_account)
>>> first_year_interest
50.0
>>> next_year_interest = my_account.send(first_year_interest + 1000)
>>> next_year_interest
102.5

def money_manager(expected_rate):
    #必须从.send()接收存款的值:
    under_management = yield                   #yield None开始。
    while True:
        try:
            additional_investment = yield expected_rate * under_management 
            if additional_investment:
                under_management += additional_investment
        except GeneratorExit:
            '''TODO: write function to send unclaimed funds to state'''
            raise
        finally:
            '''TODO: write function to mail tax info to client'''
        

def investment_account(deposited, manager):
    '''very simple model of an investment account that delegates to a manager'''
    #必须将管理员排队:
    next(manager)      #<-与manager.send相同(无)
    #这是我们将初始存款发送给经理的地方:
    manager.send(deposited)
    try:
        yield from manager
    except GeneratorExit:
        return manager.close()  # 代表?

而现在我们可以将功能委托给一个子生成器,它可以像上面一样被生成器使用。

my_manager = money_manager(.06)
my_account = investment_account(1000, my_manager)
first_year_return = next(my_account) # -> 60.0

现在模拟再往账户里加1000,加上账户的收益(60.0)。

next_year_return = my_account.send(first_year_return + 1000)
next_year_return # 123.6
my_account.close()

你也可以抛出一个异常,这个异常可以在生成器中处理或传播给用户。

import sys
try:
    raise ValueError
except:
    my_manager.throw(*sys.exc_info())
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
  File "<stdin>", line 6, in money_manager
  File "<stdin>", line 2, in <module>
ValueError

该语法目前允许列表理解中的任何表达。

expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) |
                     ('=' (yield_expr|testlist_star_expr))*)
...
yield_expr: 'yield' [yield_arg]
yield_arg: “来自”测试| 测试清单

例如,这意味着 range 对象不是 Iterator ,即使它们是可迭代的,因为它们可以被重用。像列表一样,它们的 __iter__ 方法返回迭代器对象。