For review: PEP 308 - If-then-else expression

Andrew Dalke adalke at mindspring.com
Sat Feb 8 09:31:59 CET 2003


Terry Reedy:
> x = cond1 ? expr1 :
>       cond2 ? expr2 :
>       cond 3? expr3 :
>                    expr4 ;
>
> I am not sure but what I would rather stick with and/or when safe
> rather then reverse order of conds and exprs.

Just guessing, but I'll bet that in most cases it was written like

color_name = (color == RED) ? "roja":
                      (color == BLUE) ? "azul":
                      (color == GREEN) ? "verde":
                      (color == BLACK) ? "negro":
                      "no sé";

If so, it can be replaced with a dict lookup, as in

color_name = {RED: "roja", BLUE: "azul",
                       GREEN: "verde", BLACK: "negro"}.get(color, "no sé")

Or perhaps it was like

size = (val < 1) ? "small":
         (val < 4) ? "medium":
         (val < 7) ? "large":
         (val < 11) ? "x-large":
         ("xx-large");

If so, this could be rewritten as

size = "xx-large"
for threshold, name in (1, "small"), (4, "medium"), (7, "large"), (11,
"x-large"):
  if val < threshold:
    size = name
 else:   # these two lines optional but faster
   break

or the more ugly (but faster for long lists)

cutoffs = (1, "small"), (4, "medium"), (7, "large"), (11, "x-large"), (None,
"xx-large")
_cutoff_keys = [x[0] for x in cutoffs[:-1]]
_cutoff_vals = [x[1] for x in cutoffs]
   ...
size = _cutoff_vals[bisect.bisect_right(_cutoff_keys, val)]

The trinary expression is, I'll grant you, easier to read.  However,
it isn't data oriented, it's control oriented.  In most cases you'll need
to read those values from a file or other source.

Yes, that trinary tree can be more complicated.  But in that case
debugging the trinary tree means breaking it down to look at the
parts, as compared to statements which would let you insert print
statements very easily.

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list