Update: This is only true for Python before version 2.5. Otherwise, ternary operators are perfectly valid. Thank you Janzert / Danmc for jumping on top of my post and correcting me. See the comments for their examples and why not to do
type(foo) == type(42) (spoiler: ducks don’t like typing)
No ternary? This surprises me. I wanted to make my code a tiny bit cleaner, and use a ternary operator, as I (somewhat) recently did with Flex. Python apparently doesn’t allow this kind of thing. Instead, one website suggested I do the following:
val = float(raw_input("Age: ")) status = ("working","retired")[val>65] print "You should be",status
Unfortunately this only works with simple examples that don’t have a problem being evaluated prior to the val>65 test. Sure it looks pretty, but it doesn’t work if you substitute it with this example:
def int_to_float(v): return (0.0, float(v))[type(v) == type(42)]
Unfortunately in this situation, if you supplied int_to_float with “a string “instead of a number, it would error out with a ValueError because it would try to evaluate int(“a string”) before looking to see if “a string” is of type int or not.
My solution? Not as pretty as I’d hoped:
def int_to_float(v): if type(v) != type(42): v = 0.0 return float(v)
Better code always appreciated. Internal progress is perfection.