(test) ? a:b

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Oct 22 20:44:20 EDT 2014


Michael Torrie wrote:

> On 10/22/2014 05:45 AM, Mark Lawrence wrote:
>>>> without not:
>>>> j = [j+1, 3][j>=10]
>>>> with not:
>>>> j = [3, j+1][not (j>=10)]
>>>>
>>>
>>> Oh it's a trick !
>>> thx
>> 
>> IMHO it's just dreadful.  Why people insist on messing around like this
>> I really don't know, it just drives me nuts.
> 
> This actually was the standard idiom used by many python programs before
> Python 2.5.  But I agree.  Don't do this anymore! Python has a ternary
> if expression. Also the ternary if expression does, I believe
> short-circuit logic, so the non-chosen path is not calculated.  This
> hack does not. Could lead to interesting bugs depending on your
> assumptions.

Working code doesn't suddenly become non-working code just because Python
adds a second way to do something. The standard idiom

    (value_if_false, value_if_true)[condition]

worked from (at least) Python 1.5 to Python 2.4, and it continues to work
today. There's nothing wrong with it: it does what it does, nothing more,
nothing less, and the only hashish part of this is that bools *are* ints,
with True == 1 and False == 0. That was heavily debated back in 2.3 or
thereabouts when bools were first introduced, and the decision made then
wasn't reverted in Python 3, so you can take it as By Design and not a
fluke of history. I think it is fair to say that Guido likes it that bools
are ints.

The older idiom isn't *exactly* the same as the ternary if operator, since
that short-circuits, but for many purposes short-circuiting is not
important or needed. If you don't need short-circuiting, or you dislike the
order of `value_if_true if condition else value_if_false`, or you need to
support Python 2.4 or older, or *simply because you like it*, there is
nothing wrong with using the older `sequence[flag]` idiom.

(It amuses me that not that many years ago the general attitude here was
that ternary if was an abomination that no right-thinking person should
ever use because the order of terms isn't identical to C, and now the
attitude seems to be that anyone *not* using ternary if is a heretic who
deserves to be set on fire :-)



-- 
Steven




More information about the Python-list mailing list