FW: [Python-Dev] conditional expressions?

Goh S H python_only at yahoo.com
Tue Oct 16 04:04:09 CEST 2001


Why not

   if <expr>: <expr> elif <expr>: <expr> else: <expr>

   e.g.

   if x==1: 'a' elif x==2: 'b' else: 'c'


   No 'then' keyword needed, look like normal python syntax.
   
"Tim Peters" <tim.one at home.com> wrote in message news:<mailman.1003177394.3900.python-list at python.org>...
> Following is good clarification from Guido (on Python-Dev) about "the rules" currently implemented by his patch.  
> 
> -----Original Message-----
> 
> Sent: Monday, October 15, 2001 3:24 PM
> Subject: Re: [Python-Dev] conditional expressions?
> 
> ...
> 
> I think you must be misunderstanding the proposal, which is to add
> 
>     if <expr> then <expr> else <expr>
> 
> as an alternative to the expression syntax.  Here's a preliminary
> patch (which I won't apply until I have more confidence that this is
> acceptable to the community):
> 
>     <http://sf.net/tracker/index.php?func=detail&aid=471421&group_id=5470&atid=305470>
> 
> The parens in this proposal (my version) act no different than any
> other use of parentheses in Python expressions.  Basically, you need
> to add parentheses to disambiguate expressions:
> 
> - if otherwise the 'if' keyword would be the start of a statement
>   (because 'if' at the start of a statement starts an if *statement*,
>   and the parser can't look ahead for the 'then' keyword);
> 
> - if the conditional expression is to be combined with a unary or
>   binary operator.
> 
> Some examples where no parentheses are needed (note that a comma binds
> less tight than a conditional expression -- same as for lambda):
> 
>     x = if 1 then 2 else 3, y
>     f(if 1 then 2 else 3, y)
>     a[if 1 then 2 else 3, y]
>     `if 1 then 2 else 3`
>     lambda: if 1 then 2 else 3
> 
> Some examples where parentheses *are* required:
> 
>     (if 1 then 2 else 3) + 4
>     a[(if i then 2 else 3) : 4]
> 
> In some situations I'm not sure what's right; The un-parenthesized
> form looks weird although it's not neede to avoid ambiguity:
> 
>     if (if 1 then 2 else 3): pass
>     print (if 1 then 2 else 3)
>     for i in (if 1 then "abc" else "def"): pass
> 
> I'd be happy to discuss this more.  I'm *not* happy with responses
> like "is this a bad joke?".  I don't understand how this could be an
> argument in the arsenal of the anti-Python league.
> 
> --Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-list mailing list