【发布时间】:2013-01-03 01:14:10
【问题描述】:
在这段代码中,为什么使用for 导致没有StopIteration
还是for 循环捕获所有异常然后静默退出?
在这种情况下,为什么我们会有多余的return??或者是
raise StopIteration 引起:return None?
#!/usr/bin/python3.1
def countdown(n):
print("counting down")
while n >= 9:
yield n
n -= 1
return
for x in countdown(10):
print(x)
c = countdown(10)
next(c)
next(c)
next(c)
假设StopIteration 被触发:return None。
GeneratorExit 是什么时候生成的?
def countdown(n):
print("Counting down from %d" % n)
try:
while n > 0:
yield n
n = n - 1
except GeneratorExit:
print("Only made it to %d" % n)
如果我手动执行:
c = countdown(10)
c.close() #generates GeneratorExit??
在这种情况下,为什么我看不到回溯?
【问题讨论】:
标签: python iterator generator stopiteration