if expression source format

lambertdw at corning.com lambertdw at corning.com
Thu Dec 11 18:04:16 CET 2008

Consider following snippets:

    # must examine code carefully to see that result has a value
    if condition:
        result = expression1
        result = another_expression
    return result

    # result has a value but difficult to understand how it comes
    result = expression1 if condition else another_expression
    return result

    # must examine code carefully to ensure that it always
    # returns a computed value
    if condition:
        return true_expression
        return false_expression

    # Ahh!  I do use this idiom quite often.
    if condition:
        return true_expression
    return default_expression

Actually, I was simply wondering if there is yet a  preferred way to
write the python ternary expression.  Samples:

# break expression near convenient max line length A)
true_expression if condition else (fa

# break expression near convenient max line length B)
# ("Humans be damned!" form.)
true_expr \
ession if cond \
ition else \
false_e \
xpressi \

# ternary nature of expression extremely visible
                  if condition else

# I use this form but not happily,
# providing functions as necessary to make it fit onto two lines
# loosely guided by the K&R admonition (or maybe it was K&P) that
# "a conditional expression is too complicated if you can't read
# it to your mother over the phone" or something like that.
(true_expression if condition
 else false_expression)

More information about the Python-list mailing list