PEP 289: Generator Expressions (please comment)

Werner Schiendl n17999950.temp.werner at neverbox.com
Mon Oct 27 09:47:17 EST 2003


Alex Martelli wrote:

> No, but, in all cases where the lack of parentheses would make the
> syntax unclear, you do need parentheses even today to denote tuples.
> Cfr:
>     [1,2,3]
> versus
>     [(1,2,3)]
> a list of three items, versus a list of one tuple.

ok, but that's the whole point (1,2,3) *is* a tuple.

but

   [(1),(2),(3)]

is the same than

   [1,2,3]

and

   [(1)]

is the same than

   [1]

if you want a 1-tuple in a list, you've to write

   [(1,)]

> 
> 
>>Maybe an alternative would be to have similar to tuples:
> 
> 
> The PEP *IS* "similar to tuples": parentheses are mandatory around a
> generator expression wherever their lack would make things unclear
> (and that's basically everywhere, except where the genexp is the
> only argument to a function call).  Hard to imagine a simpler rule.
> 

With "similar to tuples" I meant the kind of indication that I want
a list with exactly one item that is a generator.

> The idea of "adding a comma" like this:
> 
> 
>>[x for x in y, ] # List containing generator
> 
> 
> feels totally arbitrary and ad-hoc to me, since there is NO other
> natural connection between genexps and commas (quite differently
> from tuples).  Moreover, it would not help in the least in other
> VERY similar and typical cases, e.g.:
> 
> [x for x in y, z,]  # ok, now what...?

That's a reasonable point of course.

To be honest, I didn't consider that as I always put the items to 
iterate over in an explicit list or tuple or have 'em already inside one.

There is no way to judge what's meant in that case, it's a little 
unfortunate that this *is* currently allowed.

So within a list literal, the parentheses are required *sigh* since the 
default would need to be that following values are the values to iterate 
over.

> No, really, this whole "trailing comma to indicate a genexp in one
> very special case" idea is sort of insane.  Compare with:
> 
> [x for x in y, z,]    # same as [y, z]
> 
> [(x for x in y, z,)]  # the [<genexp>] case
> 
> [(x for x in y), z,]  # the [<genexp>, z] case
> 
> what could possibly be clearer?  Not to mention the parens rule
> is simple, universally applicable, breaks no backwards compat,
> AND is far closer to the general case for tuples ("parens when
> needed for clarity") than the "singleton tuple" case you seem
> to have focused on.

The trailing comma rule *is* there in the language already.

The problem with my idea is with the possibility of a tuple without 
parentheses in a list comprehension (as discussed above).


Still I do not like the follwing example from the specification:

g = (x**2 for x in range(10))

Whatfor are the parens?

To me this looks like requiring parens for

a = b + c


best regards

Werner





More information about the Python-list mailing list