Dangerous behavior of list(generator)

exarkun at twistedmatrix.com exarkun at twistedmatrix.com
Sun Dec 13 09:35:21 EST 2009


On 08:45 am, tjreedy at udel.edu wrote:
>Tom Machinski wrote:
>>In most cases, `list(generator)` works as expected. Thus,
>>`list(<generator expression>)` is generally equivalent to `[<generator
>>expression>]`.
>>
>>Here's a minimal case where this equivalence breaks, causing a serious
>>and hard-to-detect bug in a program:
>>
>>   >>> def sit(): raise StopIteration()
>
>StopIteration is intended to be used only within the .__next__ method 
>of iterators. The devs know that other 'off-label' use results in the 
>inconsistency you noted, but their and my view is 'don't do that'.

Which is unfortunate, because it's not that hard to get StopIteration 
without explicitly raising it yourself and this behavior makes it 
difficult to debug such situations.

What's with this view, exactly?  Is it just that it's hard to implement 
the more desirable behavior?

Jean-Paul



More information about the Python-list mailing list