Proposed PEP for a Conditional Expression

Rainer Deyke root at rainerdeyke.com
Thu Sep 13 22:45:26 EDT 2001


"Greg Ewing" <greg at cosc.canterbury.ac.nz> wrote in message
news:3BA13B35.991482C4 at cosc.canterbury.ac.nz...
> Rainer Deyke wrote:
> >
> > I was actually considering the following interpretations:
> >
> > [(<expr> for i in range(5)) if <cond> else <expr>]
>
> That one isn't even an interpretation, it's nonsense.

Just because it isn't legal Python (now or with conditional statements)
doesn't mean it's nonsense.

> Unless you mean it to mean
>
>   [<expr> for i in range(5)] if <cond> else [<expr>]

Yes, that is what I mean.

> and I wouldn't mind in the least being required to
> write it like that if that's what I wanted.

You're not addressing the real point.  With the '<expr> if <cond> else
<expr>' syntax, an 'if' enclosed in brackets has two very different meanings
depending on whether or not there is an else.  This makes Python harder to
read, write, and grok - *unless* the new syntax is somehow conceptually
unified with the list comprehension syntax.


One problem is that list comprehension syntax is already confusing:

  [i for i in range(5)]

It's easy to think of 'i for i in range(5)' as an expression that yields
multiple values and can therefore only exist in the special context of a
list literal.  This view is unfortunately incorrect:

  [(x, y) for x in range(5) for y in range(5)]

My instincts tell me that '(x, y) for x in range(5)' is evaluated for each
'y' in 'range(5)', but in fact it's the other way around: 'for x in
range(5)' is the outer loop and 'for y in range(5)' is the inner.  The 'for'
and 'if' clauses in a list comprehension do not act like expressions.
Imagine then the confusion if the '<expr> if <cond> else <expr>', which
*does* act like an expression, was added to the language.


--
Rainer Deyke (root at rainerdeyke.com)
Shareware computer games           -           http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor





More information about the Python-list mailing list