waving android

I am currently a software engineer at Google, where as a member of the Android platform team I build frameworks and user interfaces.

The blog here at is mostly historical; you can find more recent posts on .

Ternary operator in Python

July 21st, 2004


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é.

newer: older: