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

Matthew Russell matthew.russell at ovi.com
Fri Sep 17 22:03:34 CEST 2010

Personally, I tend to always add parens to tuple expressions since
it removes any and all ambiguity about when they're required or ney.

I'd actually prefer it if parens were always required, but can
appreciate that might/would offend those who prefer otherwise.

>>> for (a, b) in d.items():
...      process(a, b)

>>> def items(t):
...    return (a, b)

Always using parens means that when refactoring one can avoid the
extra mental step of 'are the parens required in use with python feature

Additionally, in some language features, the use of parens has become
required to squash warts:

>>> try:
...    a = b[k]
>>> except (KeyError, IndexError), no_item:
...    a = handle(no_item)


On Fri, 2010-09-17 at 12:44 -0700, 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.
> Raymond
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas

Ovi Mail: Making email access easy

More information about the Python-ideas mailing list