【问题标题】:StopIteration from "yield from"StopIteration from \"yield from\"
【发布时间】:2023-01-25 04:25:48
【问题描述】:

这里是发电机的新手。我的理解是,当从生成器函数 (total_average) 中断时,它将隐式触发 wrap_average 中的 StopIteration。但是 wrap_average 将 None 返回给调用者,程序不应该看到 StopIteration

def total_average():
    total = 0.0
    count = 0
    avg = None
    print("starting average generator")
    while True:
        num = yield avg
        if num is None:
            break
        total += num
        count += 1
        avg = total/count

def wrap_average(average_generator):
    """This is just a pipe to the generator"""
    print("starting wrap_average")
    avg = yield from average_generator

# Note: total_average() is the generator object. total_average is generator function
w = wrap_average(total_average())
# Execute everthing until hitting the first iterator. None being returned
print("starting the generator: ", next(w))
print(w.send(3))
print(w.send(4))
# Finish Coroutine
# ? Not sure why w.send(None) is giving me stop iteration?
w.send(None)

但是,Python 3.8 显示 StopIteration 错误。我不确定为什么?

【问题讨论】:

  • But wrap_average will return None back to the caller, and the program should not see StopIteration. wrap_average 是生成器,因此抛出此异常。返回值无关紧要。
  • “但是 wrap_average 将 None 返回给调用者,”不,wrap_average 是一个生成器函数,它返回一个生成器对象.

标签: python-3.x


【解决方案1】:

wrap_average 中的yield from 确实从total_average 捕获了StopIteration,但这不是这里唯一的StopIteration,因为total_average 不是唯一的生成器。

wrap_average也是发电机.当它结束时,它也会引发StopIteration那是你从最后的send 得到的StopIteration

【讨论】:

    猜你喜欢
    • 2019-05-10
    • 2020-05-25
    • 2014-01-10
    • 2019-04-07
    • 2020-05-09
    • 2014-04-22
    • 2021-09-30
    • 2016-08-03
    • 1970-01-01
    相关资源
    最近更新 更多