Sep 12, 2010

A little on ternary operator

Well, what I don't like about Python, it's the ternary operator. Comparing to simplicity and elegance of C's ?:, statements like expr1 if condition else expr2 make me sick. 

There are two alternatives to it, but both of them have their drawbacks.

The first one, is so called and-or trick: condition and expr1 or expr2. It behaves exactly the same as if-else, in 99%. In remaining 1% it will drive you mad finding the bug: if expr1 evaluates to false, the result will always be expr2!

And another one is: (expr2, expr1)[condition], however it's usage implies two things: 
a) condition must be a pure boolean or an int with the value of zero or one;
b) expr2 and expr1 are evaluated always, in contrary with two previous approaches.

So far, I'll stick to standard ternary operator anyway. Maybe in the end, I'll like it.

No comments:

Post a Comment