[Python-ideas] Ternary conditional operator [was Re: except expression]

Chris Angelico rosuav at gmail.com
Wed Feb 19 14:43:37 CET 2014


On Thu, Feb 20, 2014 at 12:23 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> If you look at (say) this page:
>
> http://en.wikipedia.org/wiki/%3F:
>
> nearly all the conditional operators apart from Python take the form:
>
>     condition SYMBOL true-expression SYMBOL false-expression
>
> usually with ? and : as the symbols.

Most of the reason for that is because they're all deriving from each
other, and if you're going to borrow syntax from someone else, you
should use the same little details. Making a ternary conditional
operator that uses ? and : just as C does, but switches the
true-expression and false-expression, would unnecessarily confuse
people. So would fiddling with its associativity, not that that
stopped PHP.

C's ternary operator reads in the same order as a classic if statement:

/* C */
if (cond)
    true_statement;
else
    false_statement;
value = cond ? true_expression : false_expression;

# Python
if cond:
    true_statement
else:
    false_statement

Perl's "shove the condition to the right hand of the page" notation
reads backward:

do_if_true if cond;

It first evaluates cond, and then may or may not evaluate do_if_true.
Python's ternary operator similarly reads in an odd order:

true_expression if cond else false_expression

evaluates from the middle out. But it's not the only thing that
evaluates backward:

>>> def foo(x):
    print("Calling foo:",x)
    return [0]
>>> foo(2)[0] = foo(1)
Calling foo: 1
Calling foo: 2

The RHS is evaluated before the LHS, yet this is not a problem to us.
(Maybe that's because it almost never matters?)

Is this something where people from a functional background approach
the problem one way, and people from an imperative background approach
it another way? Personally, I like my code to read more-or-less in the
order it's written: top-to-bottom, left-to-right. Definitions before
usage. But maybe that's because I grew up with a strongly imperative
style.

ChrisA


More information about the Python-ideas mailing list