"conditionals" in expressions

Python's "if" is a _statement_, and there is no conditional _operator_ (like C's "a?b:c" ternary) that we could use where expressions are needed (lambdas, etc); however, with some due care, equivalents can easily be coded.


Python lacks a ternary operator like C's cond?iftrue:iffalse -- and generally it's all the better off for that; in the rare cases where it's needed (because 'if-else' is a _statement_, and we need something that fits into an _expression_ instead), we can synthesize it with indexing, or, when shortcircuiting is needed to avoid evaluating an incorrect expression, with the 'and' and 'or' operators.

The short-circuit case can be tricky indeed, because the 'iftrue' part could be 0 (or some other 'false' value); wrapping iftrue and iffalse up into one-element (thus non-empty, thus 'true') lists, and indexing the result, avoids this further risk of anomaly.

Such tricky subtleness can hardly ever meet the prime guideline of programming, "Do the Simplest Thing that Can Possibly Work", particularly because it's likely to be conjoined with 'lambda' or other subtlety-prone constructs. 99.44 times out of 100, you will be better off passing a named local function, with a plain if/else statement. But, for the remaining 56 cases out of 10,000, these idioms can still be useful.

# with an if-else:
def foobar(whop):
    if whop>"pohrw": return "foox"
    else: return "barbar"

# the equivalent in expression-form:
foobar = lambda whop: ("foox", "barbar")[whop<="pohrw"]

# in general, we MUST ensure the 'conditional' turns
# into a 0 or 1 -- the 'not' operator is handy for that:
# not needed in the if-else case:
def plok(anything):
    if anything: return "xok"
    else: return "plik"

# but necessary when moving to expression-form:
plok = lambda anything: ("xok", "plik")[not anything]

# sometimes we need the shortcircuiting operators, 'and'
# and 'or', to avoid evaluating an incorrect expression:
def zod(plud):
    if plud: return 16+4/plud
    else: return 23

# must use and & or, NOT (...)[], as the operator-idiom:
zod = lambda plud: (plud and (16+4/plud)) or 23

# but if (16+4/plud)==0 [plud == -0.25] this erroneously
# returns 23!  A full solution ALSO requires indexing:
zod = lambda plud: ((plud and [16+4/plud]) or [23])[0]
# since the non-empty list [16+4/plud] is always 'true'

code.activestate.com ↗