你可以试着抓住他
GeneratorExit
:
class A:
def __iter__(self):
# You need to adapt this to your actual __iter__ implementation:
i = 0
try:
while i < 5:
yield i
i += 1
except GeneratorExit:
print("GeneratorExit")
如果不将发电机存放在
# If you break in any of these two loops, you'll get GeneratorExit printed:
a = A()
for i in a: ...
for i in A(): ...
如果你把发电机放在仓库里,你会发现
发电机退出
仅当发电机被垃圾收集而未耗尽时:
a = A()
it = iter(a)
for i in it:
if i == 2:
break # Does not print GeneratorExit.
it = iter(a) # Prints GeneratorExit.
在任何情况下,如果发电机还活着,您可能不想清理,否则这会变得很奇怪:
it = iter(A())
for i in it:
if i == 2:
break
for i in it: # What happens here if you cleaned-up?
pass