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

Steven D'Aprano steve at pearwood.info
Wed Feb 19 14:23:00 CET 2014


I agree with Paul that this is a tangent. Just to answer his questions:


On Wed, Feb 19, 2014 at 01:01:34PM +0000, Paul Moore wrote:
> On 19 February 2014 12:46, Steven D'Aprano <steve at pearwood.info> wrote:
> > But in Python, the ternary if operator has the condition listed in the
> > middle:
> >
> >     true-statement if cond else false-condition
> >     ..................^^^^ evaluate this first
> >
> >
> > This truly is an odd duck. It works, at least for English speakers, but
> > it is very different from most ternary operators, which evaluate the
> > left-most operand first, not the middle one. So if we were to make the
> > except operator follow the lead of if, it would look something like this:
> >
> >     exception except expr <whatever> default
> >     .................^^^^ evaluate this first
> >
> >
> > which is awful. So I reject your premise that we ought to make the
> > except ternary operator look like the if ternary operator.
> 
> I think this is pretty much a tangent by now, but your interpretation
> here isn't the only way of looking at things. Consider the following
> alternative way of looking at it
> 
>     TRUE-EXPR if COND else FALSE-EXPR
> 
> Here, TRUE-EXPR is the "expected" result, qualified by the possibility
> that if COND isn't true then FALSE-EXPR is the result. Looking at the
> if expression in that way, the parallel with the exception expression
> is much clearer:
> 
>     EXPR except EXCEPTION return FALLBACK
> 
> Here, EXPR is the "expected" result, but if you get EXCEPTION when
> evaluating it then use FALLBACK instead. (Feel free to replace
> "return" with colon or your favourite syntax alternative).

Okay, that's reasonable.


> I can't think what you mean by "most ternary operators" unless you're
> referring to ternary operators in languages other than Python, so I
> won't comment on that part of what you say.

Yes. I suggested that Python's conditional operator "is very different 
from most ternary operators" in that the condition is in the middle 
rather than on the left. I don't mean that as a negative, I actually do 
think it works well for if/else, but it is certainly different from what 
other languages do.

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. (I'm excluding those languages that 
use functional notation.) Coffeescript is a exception:

    SYMBOL condition SYMBOL true-expression SYMBOL false-expression

Likewise, the BETWEEN ternary operator in SQL looks like

    value BETWEEN low AND high


But as you say, this is a tangent.


-- 
Steven


More information about the Python-ideas mailing list