給出一個簡單的發電機:如果調用者對其調用close(),生成器是否可以注意到?
def myGenerator(max):
for i in range(max):
yield i
它可以用於像:
>>> gen = myGenerator(10)
>>> next(gen)
0
>>> next(gen)
1
當我在StopIteration
例外,對發電機進行close()
,所有後續調用next
結果。
>>> gen.close()
>>> next(gen)
StopIteration exception
發電機可以注意嗎? yield
不會引發異常。我在尋找類似:
def myGenerator(max):
for i in range(max):
try:
yield i
except CloseIteration as ex:
print("I got closed")
關閉我的頭頂 - 我認爲'gen.close( )''有效''gen.throw(GeneratorExit)'......一段時間沒有必要考慮它 - 或者我可能正在考慮一個PEP - 呃... –
是的,它是'GeneratorExit' - [ RTFM](https://www.python.org/dev/peps/pep-0342/)。 – jonrsharpe
@jonrsharpe謝天謝地 - 我現在還沒有完全老年化:p –