[Python-ideas] except expression

Paul Moore p.f.moore at gmail.com
Wed Feb 19 14:01:34 CET 2014


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).

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.

That may not be how *you* think of the if expression, but it's how I
think of it (more accurately, it's how I learned to think of it as
part of understanding why Guido chose that option).

Paul


More information about the Python-ideas mailing list