I just came across this idiom in some open-source Python, and I choked on my drink.
Rather than:
if isUp: return 'Up' else: return 'Down'
or even:
return 'Up' if isUp else 'Down'
the code read:
return isUp and 'Up' or 'Down'
I can see this is the same result, but is this a typical idiom in Python? If so, is it some performance hack that runs fast? Or is it just a once-off that needs a code review?
The ‘a and b or c’ idiom was the canonical way to express the ternary arithmetic if in Python, before PEP 308 was written and implemented. This idiom fails the ‘b’ answer is false itself; to support the general case, you could write
An alternative way of spelling it was
which, with the introduction of the bool type, could be rewritten as
(in case it isn’t clear: the conversion to bool, and the not operator, is necessary if a is not known to be bool already)
Today, the conditional expression syntax should be used if the thing must be an expression; else I recommend to use the if statement.