[Python-3000] Is this a bug with list comprehensions or not?

Stefan Behnel stefan_ml at behnel.de
Sat Jul 12 05:59:07 CEST 2008

Adam Olsen wrote:
> On Fri, Jul 11, 2008 at 6:11 PM, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
>> Stefan Behnel wrote:
>>> While I agree with this being bad design, I do think that the above is a
>>> bug.
>>> It's a different thing if the iterable in the list comp/genexp raises a
>>> StopIteration, or if the conditional does it. And not silently catching
>>> anything raised by the latter sounds like the right thing to me.
>> From some experiments I just did using bare genexps and calling
>> next() on them, I don't think anything is being silently caught
>> in the genexp. What's happening is that the surrounding list()
>> constructor is performing another level of iteration over the
>> results of the genexp, and *that* is what's being stopped by
>> the StopIteration.
>> I don't see how this can be fixed, because there's no way for
>> the list() constructor to know where the StopIteration is coming
>> from.

That makes sense. In that case, I consider the genexp behaviour correct, as it
just passes on the raised exception, without caring about its type.

> It can be fixed in the genexp by declaring it erroneous and raising a
> RuntimeError when encountered.  The list() constructor will see the
> RuntimeError instead, which will get propagated properly.

I think this kind of special casing would make the interface worse than it
currently is. If this is the only way to work around weird code, I'd rather
let people raise plain StopIterations if they think they have to, without
caring about it any further in the genexp implementation.


More information about the Python-3000 mailing list