As you’ve probably noticed over the last few days, I like Python a lot.
Last night I found a new (to me) thing. It’s a new to Python 2.5, which might preclude it from being useful in older projects. In C and C++, one of the more useful constructs in expressions is the ternary operator:
minimumOfXandY = (x < y) ? x : y;
In Python prior to 2.5 you could use the fact that the logical and and or features test for truth,
but return the actual objects involved — a little counterintuitively you would write:
minimumOfXandY = (x < y) and x or y
In Python 2.5 there’s a slightly more readable syntax:
minimumOfXandY = x if (x < y) else y
I don’t think it’s quite as nice as the C style way of doing things, as the values and the conditional are in a non-intuitive order
for imperative languages. But arguably it’s a little better than the and/or idiom.
Matt Godbolt is a C++ developer living in Chicago. He works for Hudson River Trading on super fun but secret things. He is one half of the Two's Complement podcast. Follow him on Mastodon or Bluesky.