首页 > 解决方案 > 自动将双向生成器推进到接受非无值的点?

问题描述

假设我们用 Python 编写了一个非常简单的双向生成器:

def share_of_total():
    s = 0
    new_num = 0
    while True:
        new_num = yield new_num / (s or 1)
        s += new_num

share_calculator = share_of_total()
next(share_calculator)  # Without this we get the TypeError

for num in [1, 2, 3]:
    print(share_calculator.send(num))

这个生成器只接受一个数字并产生一个浮点数,表示它在所有先前提供的数字总和中所占的份额。

理想情况下,我们希望立即使用它,如下所示:

share_calculator = share_of_total()
print(share_calculator.send(num))

但是,这会导致TypeError: can't send non-None value to a just-started generator. 的所有用户share_of_total()必须记住next(share_calculator)在生成器按预期使用之前执行。

有没有一种优雅的方式可以share_calculator立即使用 - 即能够share_calculator.send(num)在创建后立即调用share_calculator

标签: pythongeneratorcoroutine

解决方案


你应该用share_calculator.send(None)

将其包装在为您创建生成器的函数中:

def get_share_calculator():
    def share_of_total():
        s = 0
        new_num = 0
        while True:
            new_num = yield new_num / (s or 1)
            s += new_num
    retval = share_total()
    retval.send(None)
    return retval

share_calculator = get_share_calculator()

for num in [1, 2, 3]:
    print(share_calculator.send(num))

推荐阅读