Iterator execution hangs after the iterator is exhausted
I have a generator function that takes iterator object and performs some logic on every item. This runs on a larger list of iterations. It then yields the result back to the calling code, so it can break the for
and while
loop
def func(it):
item = next(it)
item = item.execute()
yield item
it = iter(range(1, 10))
condition = True
while condition:
for item in func(it):
condition = item
print condition
Executing this code in Python IDLE, prints the follows and hangs:
1
2
3
4
5
6
7
8
9
I need to CTRL+C to break out the loops. If I use regular range(10) so the loop starts with the value 0, it breaks immediately (since condition=0
) and return prompt.
What am I missing? Why my iterator hangs when exhausted?
The iterator isn't the one hanging, it's your while
loop. Since condition
ends at 9
, the while loop becomes while 9
which never exits. Take out the while loop completely.
for item in func(it):
condition = item
print condition
Or, if you want to stop if the condition is false, then:
for item in func(it):
condition = item
print condition
if not condition: break
The for loop is not hanging. The outer while loop is. You have set it to run forever as condition changes from 1-9 and then remains as 9. So, code executes to:
while 9
which always returns True and this becomes an infinite loop.
链接地址: http://www.djcxy.com/p/53480.html上一篇: 在迭代f.next()时重绕多行
下一篇: 迭代器耗尽后,迭代器执行会挂起