Idioms combining 'next(items)' and 'for item in items:'
Terry Reedy
tjreedy at udel.edu
Sun Sep 11 20:45:41 EDT 2011
On 9/11/2011 6:41 PM, Chris Angelico wrote:
> On Mon, Sep 12, 2011 at 2:47 AM, Terry Reedy<tjreedy at udel.edu> wrote:
>> What you are saying is a) that the following code
>>
>> for title in ['amazinG', 'a helL of a fiGHT', '', 'igNordEd']:
>> print(fix_title(title))
> At least in Python 3.2, this isn't the case. StopIteration breaks the
> loop only if it's raised during the assignment, not during the body.
It breaks the loop *silently* only if ...
>>>> x=iter([1,2,3,4,5])
>>>> for i in x:
> print("%d - %d"%(i,next(x)))
>
> 1 - 2
> 3 - 4
> Traceback (most recent call last):
> File "<pyshell#281>", line 2, in<module>
> print("%d - %d"%(i,next(x)))
> StopIteration
whereas, you are right, it breaks it noisily in the body. So Ian's claim
that StopIteration must be caught to avoid silent termination is not
true. Thanks for pointing out what I saw but did not cognize the full
implication of before. A better exception and an error message with an
explaination might still be a good idea, though.
--
Terry Jan Reedy
More information about the Python-list
mailing list