Nested iteration?

Chris Angelico rosuav at gmail.com
Tue Apr 23 12:42:41 EDT 2013


On Wed, Apr 24, 2013 at 2:30 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On Tue, Apr 23, 2013 at 10:21 AM, Chris Angelico <rosuav at gmail.com> wrote:
>> The definition of the for loop is sufficiently simple that this is
>> safe, with the caveat already mentioned (that __iter__ is just
>> returning self). And calling next() inside the loop will simply
>> terminate the loop if there's nothing there, so I'd not have a problem
>> with code like that - for instance, if I wanted to iterate over pairs
>> of lines, I'd happily do this:
>>
>> for line1 in f:
>>   line2=next(f)
>>   print(line2)
>>   print(line1)
>>
>> That'll happily swap pairs, ignoring any stray line at the end of the
>> file. Why bother catching StopIteration just to break?
>
> The next() there will *not* "simply terminate the loop" if it raises a
> StopIteration; for loops do not catch StopIteration exceptions that
> are raised from the body of the loop.  The StopIteration will continue
> to propagate until it is caught or it reaches the sys.excepthook.  In
> unusual circumstances, it is even possible that it could cause some
> *other* loop higher in the stack to break (i.e. if the current code is
> being run as a result of the next() method being called by the looping
> construct).

Ah, whoops, my bad. This is what I get for not checking. I know I've
done weird stuff with for loops before, but I guess it was fiddling
inside the top of it, not in its body.

I love this list. If I make a mistake, it's sure to be caught by
someone else. The record is guaranteed to be set straight. Thanks Ian!

ChrisA



More information about the Python-list mailing list