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

Nick Coghlan ncoghlan at gmail.com
Sat Jul 12 02:50:59 CEST 2008


Carl Johnson wrote:
> Certainly, it's an inconsistency compared to generator expressions, but 
> is it a bug? I know that Python 3000 is making it so that list 
> comprehension variables don't leak anymore, so I take it that the goal 
> is to have them be more similar to generator expressions than not. Then 
> again, maybe there are good reasons for this behavior? My own feeling is 
> that these two cases should behave the same way, but I could be wrong.

Comprehensions and generator expressions in Py3k are more similar than 
they are in 2.x, but they still aren't identical.

[x for x in range(10) if f(x)] is shorthand for:

   def _f(itr):
       _[1] = []
       for x in itr:
           if f(x):
               _[1].append(x)
       return _[1]
   expr_result = _f(range(10))

While (x for x in range(10) if f(x)) is shorthand for:

   def _g(itr):
       for x in itr:
           if f(x):
               yield x
   expr_result = _g(range(10))

 From those expansions, I think it's pretty clear that the implicit 
generator function in the second case is going to swallow the 
StopIteration and treat it as the end of the iteration process, but no 
such thing is going to happen with the implicit standard function in the 
list comprehension case.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-3000 mailing list