ternary operator

John Roth johnroth at ameritech.net
Tue Feb 4 18:05:05 EST 2003


"David Gausebeck" <gausebec-spam at paypal.com> wrote in message
news:3e404255.1172145764 at news.cis.dfn.de...
> I've recently started using python from a primarily C/C++ background,
> and one of the annoyances that I ran into right away was the lack of a
> ternary ?: operator.
>
> After looking around a little, I found a number of discussions by
> others who have had the same problem.  There are a few workarounds for
> it, but none are very good.
>
> The C expression "a ? b : c" can be emulated in python with
> "a and b or c"
> if b is not false.  If b could be false, then you can use
> "(a and [b] or [c])[0]".

That's the accepted workaround. I don't think anyone likes it.

> In addition to the second (safer) form being fairly ugly, both
> versions make for code that's awkward to read, as they're using 'and'
> and 'or' to return values rather than evaluate truth.

Well, that's not really that much of a problem, since you see the
same thing in other contexts. The odd behavior of 'and' and 'or'
is one of those things that makes Python something more than
"just another language."

It's used, for example, to provide defaulting.

> The other alternative is to declare a function f(a, b, c) which
> returns the desired value.  The problems with this are that it isn't
> standard (so code using it wouldn't be quite as easy to read), and
> that it would have to be declared over and over.

As you point out, this doesn't short circuit, unless you define 'b' and
'c' using lambdas. That's megaugly.

> So, a couple questions:
>
> 1) Is the lack of a ternary operator widely considered a (minor)
>    shortcoming of python, or is it just a few holdouts from C/C++ who
>    care?

It certainly isn't enough of a shortcoming to drive people away in
droves.

> 2) Is there any better workaround than the ones I've listed above?

Not that I've heard of.

> Finally, a thought on the solution I'd like to see...  I agree that
> the C syntax of a ? b : c wouldn't really work nicely in python, but
> perhaps a unary ? operator acting on a list/tuple would.  Instead of
> "a ? b : c", python could support
> "?(a, b, c)".
>
> The main disadvantage I can see to the syntax at this point is that it
> wouldn't support short-circuiting. You also run into the ambiguity
between tuples and function parameter lists. If '?' is an operator,
that's
a tuple, but if it's a wierd function name, that's a parameter list.

You might have more luck pursuing lazy evaluation in functions.
If you have that, a functional version of if, in a similar style to TCL,
would be incredibly easy to write. This would, of course, also support
elif.

John Roth
>
> -Dave






More information about the Python-list mailing list