Generator expression parenthesis mixed with function call ones
Laurent Pointal
laurent.pointal at wanadoo.fr
Wed Mar 7 13:21:57 EST 2007
Gabriel Genellina wrote:
> En Wed, 07 Mar 2007 12:53:43 -0300, Laurent Pointal
> <laurent.pointal at limsi.fr> escribió:
>
>>>>> f(4,i for i in range(10))
>> File "<stdin>", line 1
>> SyntaxError: invalid syntax
>
> 2.5 has a better error message:
> py> f(4,i for i in range(10))
> File "<stdin>", line 1
> SyntaxError: Generator expression must be parenthesized if not sole
> argument
>
>> Why does Python allow generator expression parenthesis to be mixed with
>> function call parenthesis when there is only one parameter ?
>
> Because they are redundant when only one argument is used.
> sum(i for i in range(10)) looks better than sum((i for i in range(10)))
> "Beautiful is better than ugly", and "Readability counts."
I complement my reply.
Beginners generally know about list-comprehensions and associate the
syntax "x for x in asequence" to a list expression. I'm not sure that
reading a "f(i for i in range(20))" they understand that they are dealing
with a different object kind.
If function f start by a if len(myparameter)...
TypeError: len() of unsized object
If function f goes among its parameter with "for x in myparameter" more than
once, other loops goes throught an empty loop.
>> IMHO this should be forbidden, usage must not be different when there is
>> only one parameter and when there are more parameters.
>
> It's similar to "%d" % 123 vs. "%d" % (123,)
> """Special cases aren't special enough to break the rules.
> Although practicality beats purity."""
In that case there cannot be confusion.
A+
Laurent.
More information about the Python-list
mailing list