Ternary operator in Python
I wish Python had (hygienic) syntactic macros, because then I’d be able to implement a proper ternary operator (by which I mean the unused branch will not be evaluated at all). As it is, the best I can do is the following:
# ifthen(t,a) evaluates to a if t, or None # ifthen(t,a,b) evaluates to a if t, or b ifthen = lambda t,a,b=None: (a,b)[not t]
Well, at least it’s pretty short. That’s something.
Update: Dave writes:
“The IAQ has a good
discussion of ternary operators in Python.” Sure enough, it does. The
author is sensitive to the idea of providing conditionally-executed
alternatives:
[lambda: result, lambda: alternative][not not test]()
… but reveals the true reason why we don’t have a ternary op:
… because Python is committed to a clear distinction between
expressions and statements …
Well, there you go. Coming from a college diet of parentheses in my
alphabet soup, this seems like a totally indefensible stance (what is a
statement but an expression with side-effects?), but the author has
anticipated this too:
If u cn rd ths, u cn gt a jb in fncnl prg (if thr wr any).
Yeah, touché.