ternary operator

David Gausebeck gausebec-spam at paypal.com
Tue Feb 4 17:44:42 EST 2003


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]".

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.

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.

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?
2) Is there any better workaround than the ones I've listed above?

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.

-Dave




More information about the Python-list mailing list