我发现了一种精巧的解决方案,可以解决在生成器耗尽之后返回最终信息的问题,该问题是将所需的内容放入StopIteration中。这要求在生成器函数的末尾手动引发Exception。但是,似乎无法从外部捕获。它的唯一工作方式是使用自定义异常,该异常会破坏对任何对返回值不感兴趣的人(例如,在for
语句中)的生成器协议。 。
def generator():
for i in range(3):
print('inside', i)
yield i
print('raising...')
raise StopIteration('<<Some accumulated result.>>')
p = generator()
try:
while True:
print('\n Trying...')
print('outside', next(p))
except StopIteration as e:
print('handling', e.arg
输出:
Trying...
inside 0
outside 0
Trying...
inside 1
outside 1
Trying...
inside 2
outside 2
Trying...
raising...
RuntimeError: generator raised StopIteration
预期输出:
Trying...
inside 0
outside 0
Trying...
inside 1
outside 1
Trying...
inside 2
outside 2
Trying...
raising...
handling ('<<Some accumulated result.>>')
实际上是生成器的返回值seems to be put inside the exception by default:
def generator():
for i in range(3):
print('inside', i)
yield i
print('raising...')
return '<<Some accumulated result.>>'
p = generator()
try:
while True:
print('\n Trying...')
print('outside', next(p))
except StopIteration as e:
print('handling', e.args)
输出:
Trying...
inside 0
outside 0
Trying...
inside 1
outside 1
Trying...
inside 2
outside 2
Trying...
raising...
handling ('<<Some accumulated result.>>')