Why doesn't StopIteration get caught in the following code?
tjreedy at udel.edu
Sun Apr 5 04:48:18 CEST 2009
>>>> while True:
> ... i = gen.next()
> ... print i
> Traceback (most recent call last):
> File "<stdin>", line 2, in ?
If you had written
for item in gen: print(i)
then StopIteration from gen would be caught.
One expansion of a for loop is (in the above case)
it = iter(gen) # not needed here, but is for general iterables
i = it.next()
print(i) # or whatever the loop body is
In other words, 'for i in iterable' expands to several lines of
boilerplate code. It is very useful syntactic sugar.
You left out the try..except part.
More information about the Python-list