现在我正在研究 yield-from 和 await 语法之间的区别。从官方 python 文档中,yield-from generator() 只是以下代码的语法糖:
for i in generator(): yield i
但是我无法在下面的示例中对 yield-from 进行脱糖。
def accumlate():
# context
accumlator = 0
while True:
next = yield
if next is None:
return accumlator
accumlator += next
def gather(tallies):
while True:
tally = yield from accumlate() # (*)
tallies.append(tally)
def main():
tallies = []
accumlator = gather(tallies)
next(accumlator)
for i in range(4):
accumlator.send(i)
accumlator.send(None)
for i in range(6, 10):
accumlator.send(i)
accumlator.send(None)
print(tallies)
if __name__ == "__main__":
main()
我试图用 for-in 版本替换 yield-from,但它不起作用,因为 for-in 不能放在 tally 变量的右侧。用星号标记的代码的确切脱糖是什么?