FW: [Python-Dev] conditional expressions?

Tim Peters tim.one at home.com
Mon Oct 15 16:22:29 EDT 2001


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