rulururu

post Emulating “?:”

July 8th, 2008

Filed under: Python — Kai @ 6:36 pm

Python doesn’t know the trinary operator “?:” from C. However, it’s pretty easy to emulate:

x ? y : z    -->    [z, y][bool(x)]

(If you’re sure that x is already a boolean type (or an integer of value 0 or 1), you can omit the bool() function, of course.)

How does the trick work?
We simply create a small list constant, containing the two values to choose from, and use the boolean as an index into the list. “False” is equivalent to 0 and will select the first element, while “True” is equivalent to 1 and will select the second one.

Note that always all three operands will be evaluated, unlike the “?:” operator in C. If you need shortcut evaluation, use an if-else statement.

Actually, there’s another way to do it with shortcut evaluation, but it only works if y does not contain a boolean False equivalent:

x ? y : z    -->    bool(x) and y or z

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

ruldrurd
Powered by WordPress, Content and Design by Kai Bellmann
Entries (RSS) and Comments (RSS)