Like most newcomers to Python, I lamented the absence of a ternary operator. Some say the operator is hard to read, but I say those people need better reading glasses. If I want to assign a value based on a condition, I don’t think there’s anything clearer than an operator triad that exists solely for that purpose.
In any case, Python doesn’t have the standard = ? : ternary. It has a similar shorthand if-else construct, which I used begrudgingly. It looks like this:
result = value1 if condition else value2THAT is hard to read. Code highlighting helps, but it’s still far from optimal.
This Kung Fu Is Weak!
Then I stumbled upon this random page while looking up exactly what the syntax was. The trick is to build a tuple on the fly and immediately select one of its elements using the condition as the index. The above code ends up looking like this:
result = (value1, value2)[condition]How fucking awesomely elegant is that? As the post title suggests, I actually like this better than the original ternary.
As if to compliment this trick, the bool type in Python actually evaluates to a numeric 0 or 1. This makes the classic “Set the value to itself if it’s already set; set it to X otherwise” case incredibly easy:
value = (value, X)[bool(value)]A frequent use case is one where you have a function argument that you want to default to a certain value calculated using another function. It can’t just be set in the function signature; you end up setting it to None in the signature (which, IMO, you should have done to begin with), then assigning it whatever the default value is if the caller doesn’t pass anything.
Here’s a real example: an implementation of Binary Search in Python. (I’ve been going through Introduction to Algorithms as part of my New Years resolution to become a better programmer; I hate writing pseudo code, so I’ve been writing Python for all the exercises)
UDPATE
Found an even better alternative for this case:
value = value or XExample updated:
def binSearch(needle, haystack, start=None, end=None): start = start or 0 end = end or len(haystack)-1Enjoy.midpt = start+int(math.floor((end-start)/2)) median = haystack[midpt] if (needle > median): return binSearch(needle, haystack, midpt, end) elif (needle < median): return binSearch(needle, haystack, start, midpt) else: return midpt