给出一个简单的生成器:
<a class="ls-sc-button default" ng-click="callJersey()">Valider</a>
可以像:
一样使用def myGenerator(max):
for i in range(max):
yield i
当我在生成器上执行>>> gen = myGenerator(10)
>>> next(gen)
0
>>> next(gen)
1
时,对close()
的所有后续调用都会导致next
异常。
StopIteration
发电机可以注意到吗? >>> gen.close()
>>> next(gen)
StopIteration exception
不会抛出异常。我正在寻找类似的东西:
yield
答案 0 :(得分:1)
正如Jon在评论中提到的calling close()
raises a GeneratorExit
exception,您可以注意:
In [1]: def mygenerator(max):
...: try:
...: for i in range(max):
...: yield i
...: except GeneratorExit:
...: print('I got closed')
...: raise
...:
In [2]: gen = mygenerator(10)
In [3]: next(gen)
Out[3]: 0
In [4]: next(gen)
Out[4]: 1
In [5]: gen.close()
I got closed