For review: PEP 308 - If-then-else expression
Andrew Dalke
adalke at mindspring.com
Sat Feb 8 02:58:00 EST 2003
Erik Max Francis
> So you'd want conditional expressions in things like [example in C]:
>
> printf("I have %d %s%s.\n", count, noun, count == 1 ? "" : "s");
>
> Here's an example where I want to do an if...else but that is really a
> minor point the big picture.
I like minor points. They are things I can understand.
So assuming you don't want to do internationalization, you could also
do this example with
print "I have %d %s%s." % (count, noun, "s"[:count!=1])
or
print "I have %d %s%s." % (count, noun, ("", "s")[count!=1])
or
print "I have %d %s%s." % (count, noun, "s" * (count != 1)
Though I would have more likely have had something like
_irregular = {
"person": "people",
"mouse": "mice"
}
_self_plural = dict.from_keys("sheep fish".split())
def pluralize(noun, count):
if count == 1 or noun in _self_plural:
return noun
if noun in _irregular:
return _irregular[noun]
if noun[-1:] in "sz":
return noun + "es"
if noun[-1:] == "y":
return noun[:-1] + "ies"
return noun + "s"
> a = c1 if e1 else \
> c2 if e2 else ...
In most of those cases, the construct is
a = "red" if color == 1 else "blue" if color == 2 else "green"
which is better (IMHO) written as
a = {1: "red", 2: "blue", 3: "green"}[color]
or
a = {1: "red", 2: "blue"}.get(color, "green")
if you don't care about error checking (note that the original
trinary expression doesn't care about error checking)
I was only somewhat joking above with the "minor points" comment.
My feeling about the trinary operator is that, yes, there are a few
places where it fits better. However,
1) people using it have a C background, and may ignore the possible
solutions available in Python (like a=[false, true][bool(expr)] and
a = x or None, or a={k1: v1, k2:v2, k3: v3}[key] )
2) the ternary expression should not be nested, because it gets too
confusing too quickly. However, it's the reading which is the
confusing part; Writing these nested expressions is really easy.
3) people (like me when I was younger) will write multiple lines
of ternary code, making "cute" but hard-to-understand code
4) it is harder to understand and debug because an if/else also
makes it easy to add print statements or other sorts of tracing
to see what's going on at a given step
5) the justification on the basis of short circuiting is not that
strong because most real-life uses of ?: do not depend on
short circuiting other than for slight (trivial) speedups.
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list