您需要迭代以执行异常。遵循最少的代码确实会引发异常。
def func(a,b):
#..do something...
yield a, b
if a!=b:
raise Exception(a,b)
[_ for _ in func(1,2)]
这与
No 'print' output when using yield?
特别是引用一个答案
"Calling a generator function as in testFunc(1) simply creates a generator instance; it does not run the body of the code."
编辑
下面说明了解决方案。这也是从上述引用的线程。
def func(a,b):
#..do something...
for i in range(10):
a+=1
yield a, b
if a>3:
raise Exception(a,b)
gen=func(1,2)
next(gen) # returns (2,2)
next(gen) # returns (3,2)
next(gen) # return (4,2)
next(gen) # returns Exception. As expected
如果你这样做了
next(func())
正如您在编辑中提到的,每次调用时都会创建新的生成器
下一个(函数())
. 相反,如上所示,先实例化它,然后调用多次。
社区wiki作为相关问题,无法在评论中添加此内容。