For review: PEP 308 - If-then-else expression
Erik Max Francis
max at alcyone.com
Sat Feb 8 03:22:55 EST 2003
Andrew Dalke wrote:
> 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)
Of course you can. But you wouldn't really suggest that these are
clearer, would you? (And, of course, a true conditional expression
would be short-circuiting, although that isn't relevant to this example
here, but is one of the big payoffs to a _real_ conditional expression.)
In my opinion, the key issue about the benefit of a conditional operator
is about making code more readable. If I see 's'[:count!=1] I certainly
have to sit and think about it a little bit; it's hardly a crystal clear
idiom. ('', 's')[count != 1] is a tiny bit better since it's a slightly
more recognized idiom (and I've certainly used it on occasion), but it's
still not immediately clear.
Using a recognized idiom that's built into the language, whether it's x
if p else y or whatever might get adopted, makes it crystal clear what I
mean. Same is with Booleans (which I also hoped for when first
encountering the language and supported the addition of one when it was
proposed); if I write return 1, I'm not sure whether that's going to be
used as a counting number, an integer, a degenerate
rational/float/complex number, a comparison result (-1, 0, +1), or a
Boolean. When I see return True, I know right away.
If I see
's'[:count != 1]
I have to sit and think.
If I see
's' if count != 1 else ''
(or whatever form gets adopted), provided I understand the form, the
intended meaning is much clearer.
Can conditional expressions be abused? You bet; but so can any other
language feature. Conditional expressions, if used properly, can make
code like your examples much clearer, because you don't have to pull a
trick to get the effect of a conditional operator, you have one already
built in.
> 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.
My example was deliberately simple, to which there are (still in my
opinion) less clear alternatives. For _real_ short circuiting, if you
want that compressed into an expression you have some real IOPyCC
contenders:
(p and [x] or [y])[0]
or the incomparable
(p and lambda: x or lambda: y)()
--
Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/ \ Ten lands are sooner known than one man.
\__/ (a Yiddish proverb)
Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/
A personal guide to Aliens vs. Predator 2.
More information about the Python-list
mailing list