Proposed PEP for a Conditional Expression
Rainer Deyke
root at rainerdeyke.com
Wed Sep 12 13:03:17 EDT 2001
"Joshua Marshall" <jmarshal at mathworks.com> wrote in message
news:9nnsa3$bjl$1 at news.mathworks.com...
> thp at cs.ucr.edu wrote:
> > Bernhard Herzog <bh at intevation.de> wrote:
> > [...]
> > : Another way that come to mind:
>
> > : <expr> if <cond> else <expr>
>
> One thing I don't like about this suggestion is that <cond> is
> evaluated before the first <expr> is [potentially] evaluated, even
> though <expr> syntactically precedes <cond>.
There is a precedent though.
[<expr> for i in [0] if <cond>]
Strangely enough, list comprehensions without 'for' are forbidden. If they
weren't, you write a conditional expression like this:
([<expr> if <cond>] + [<else-expr> if not <cond>])[0]
This is very ugly (and evalutes <cond> twice). If the '<expr> if <cond>
else <expr>' form was accepted, it would be syntactically consistent with
for-less list comprehensions:
[<expr> if <cond>] # for-less list comprehension
[<expr> if <cond> else <expr>] # list literal
However, it would not fit well with list comprehensions that have a 'for':
[<expr> if <cond> for i in range(5)] # Syntax error
[<expr> for i in range(5) if <cond> else <expr>] # Syntax error
# and ambiguous intent
Conclusion: any conditional expression syntax that uses the 'if' keyword is
likely to be confusing if used in a list comprehension. Maybe this
confusion could be avoided by carefully updating the list comprehension
syntax.
--
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