[Python-ideas] New 3.x restriction in list comprehensions

MRAB python at mrabarnett.plus.com
Fri Sep 17 22:27:37 CEST 2010


On 17/09/2010 20:44, Raymond Hettinger wrote:
> In Python2, you can transform:
>
>    r = []
>    for x in 2, 4, 6:
>         r.append(x*x+1)
>
> into:
>
>     r = [x*x+1 for x in 2, 4, 6]
>
> In Python3, the first still works but the second gives a SyntaxError.
> It wants the 2, 4, 6 to have parentheses.
>
> The good parts of the change:
>   + it matches what genexps do
>   + that simplifies the grammar a bit (listcomps bodies and genexp bodies)
>   + a listcomp can be reliably transformed to a genexp
>
> The bad parts:
>   + The restriction wasn't necessary (we could undo it)
>   + It makes 2-to-3 conversion a bit harder
>   + It no longer parallels other paren-free tuple constructions:
>          return x, y
>          yield x, y
>          t = x, y
>             ...
>   + It particular, it no longer parallels regular for-loop syntax
>
> The last part is the one that seems the most problematic.
> If you write for-loops day in and day out with the unrestricted
> syntax, you (or least me) will tend to do the wrong thing when
> writing a list comprehension.  It is a bit jarring to get the SyntaxError
> when the code looks correct -- it took me a bit of fiddling to figure-out
> what was going on.
>
> My question for the group is whether it would be a good
> idea to drop the new restriction.
>
Listcomps look more like genexps than for loops, so they should
probably have the same syntax retrictions (or lack of), IMHO.



More information about the Python-ideas mailing list