Defending the ternary operator

Andrew Koenig ark at research.att.com
Sat Feb 8 13:30:35 EST 2003


>> As an experiment, I went back through a 2800-line C program that I
>> wrote about 20 years ago (!) to see how often I used ?: and in what
>> context.  I figure that reading my own 20-year-old code is probably a
>> lot like reading some else's code.

Laura> The fact that you would not abuse a ternary does nothing to put
Laura> my mind at rest.  I've wished for a world where all the C and
Laura> C++ programs I have encountered have been written by you, many
Laura> times, sometimes in those exact words, as well.

I'm flattered :-)

Laura> If you don't think that it will be used very often, do you
Laura> admit that it might be on the side of 'diminishing returns', a
Laura> feature request that doesn't 'pull enough weight' to be worth
Laura> doing?  Or do you think that any language feature that is of
Laura> use to somebody should automatically go into a language to 'add
Laura> desired functionality'?  I doubt very much that you believe
Laura> this, (though if you do, we have found the disagreement, for
Laura> certain).  How do you determine if a proposed language feature
Laura> 'pulls enough weight'?

One way is by considering the alternatives.

For example, suppose I want to write

    z = max(x, y)

without calling a function.  Yes, I know that's contrived, but examples
often are.  I would like to be able to write

    z = x if x > y else y

Today I can't.  What can I do?  I can write

    if x > y:
        z = x
    else:
        z = y

in which I must utter "z" twice and might get it wrong one of those times.
Or I can write

    z = (x, y)[x <= y]

which evaluates x and y twice, and in which I must remember to invert
the condition.  Or I can write

    z = { True: x, False: y }[x > y]

which still evaluates x and y twice, and is getting wordy.

Or -- and this is what really convinces me -- I can write

    z = x > y and x or y

which looks really cool, and is just plain wrong, because if x is
0 and y is negative, the result is 0 instead of y.

It's this last example that really horrifies me, because people see
it, think that "if a then b else c" should be written as
"a and b or c", and then get into trouble.

The fact that people are suggesting such circumlocutions says to me
that there is a use for the feature, and the fact that people are
suggesting incorrect circumlocutions makes my skin crawl.

-- 
Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark





More information about the Python-list mailing list