[Python-Dev] conditional expressions?

Tim Peters tim.one@home.com
Mon, 15 Oct 2001 19:30:58 -0400


||| ...
||| Some examples where parentheses *are* required:
|||
|||     (if 1 then 2 else 3) + 4

|| But that's because it's a top-level expression beginning with "if", not
|| because of the "+", right?  In the patched Python, this works fine:
||
|| >>> x = if 0 then 2 else 3 + 4
|| >>> x
|| 7
|| >>>

| But it groups differently: the 'else' part is '3 + 4' here.  Try 'if
| 1'. :-)

Yes, I understand how it groups, and am fine with it.  The question I asked
is the one I asked <wink>:  the paretheses aren't required because of the
"+", but solely because it's a "top-level expression".  This is by way of
contrast with the example that was next to it in the original:

    a[(if i then 2 else 3) : 4]

where, unlike the "+" example, the parens are also required if you stick
that on the RHS of an assignment.

I thought both were *intended* to be examples of:

    you need to add parentheses to disambiguate expressions:
    ...
    - if the conditional expression is to be combined with a unary or
      binary operator.

as "+" and ":" both feel like <wink> binary operators in these examples.

|| OTOH, these seem odd:
||
|| >>> 4 + if 1 then 2 else 3
||   File "<stdin>", line 1
||     4 + if 1 then 2 else 3
||          ^
|| SyntaxError: invalid syntax

> That's too much work for the parser to get right.  And you'd get
> anomalies like
>
>     3 * if 1 then 2 else 3 + 4
>
> -- how should this group?

That's a good point.

> ...
> Because the conditional *ends* in something that "pulls in" all
> following binary operators and their operands until it hits a ")",
> I find it safer not to let it accept an operator at the front.

I agree.  The "precedence pull" of "*" does make it more tempting to misread

    x = 3 * if 1 then 2 else 3 + 4

than to misread

    x = if 1 then 2 else 3 + 4

and I'm personally happier with "excess" parentheses anyway.