委托生成器中的“ yield from”语句是否会自动为其委派的子生成器加注?

时间:2019-06-12 10:37:47

标签: python python-3.x generator coroutine

我确实需要显式初始化delegating_generator,但是我不需要对sub_generator进行初始化。为什么会这样,“ yield from”关键字组合是否隐式地将其委派给其sub_generator?

PEP 380-委托给子生成器的语法 https://www.python.org/dev/peps/pep-0380/

def caller(return_value):
    delegating_gen = delegating_generator(return_value)
    next(delegating_gen) # priming the delegating generator

    # Here send some values to the subgenerator
    delegating_gen.send('some data for the subgenerator')

    delegating_gen.send(None) # terminate the subgenerator
    return return_value

def delegating_generator(return_value):
    while True:
        return_value = yield from sub_generator()

def sub_generator():
    total = 0
    while True:
        value = yield
        if value is None:
            break
        total += value
    return total

0 个答案:

没有答案