No ternary operator in Python

September 10, 2008


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

–wellho.net

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.


2 Responses to

“No ternary operator in Python”

  1. Janzert Says:

    The ternary operator was added in 2.5, the form is:

    true_val if condition else false_val

    so:

    def int_to_float(v):
    return 0.0 if type(v) != int else float(v)

    If you need to be compatible with older versions though you are stuck of course. Also as you probably know but just as a note for anyone that happens across this, direct type comparisons as used in the examples above are discouraged since it will break any chance of duck types working.

  2. Dan Says:

    yes, python has a ternary.

    expr-1 if bool-expr else expr-2

    def int_to_float(v):
    return float(v) if isinstance(v, int) else 0.0