PEP 308: A PEP Writer's Experience - PRO
Michael Chermside
mcherm at destiny.com
Sat Feb 8 11:12:02 EST 2003
In late 2001, when I was young and foolish (NOTE: I still am), I
tried writing a PEP for a ternary expression. I attempted to get
a consensus on c.l.py, and then write up that consensus, and of
course I failed utterly to obtain any sort of consensus, so it
never got completed. The only thing I really accomplished was to
convince MYSELF what should be done and the reasons why. I share
that with you now in hopes that it will convince people that
we should accept PEP 308.
There are lots of arguments in favor of a ternary expression,
but there are just two which I feel are quite convincing.
[1] It makes expressions more powerful.
If a ternary expression is available, then things can be done in
expressions which would be impossible without it. lambda is the
example most often given, but I think a different example is
more compelling. Suppose you want to write a line of logging
into your program:
print "x = " + x.getDisplayString()
but you have to allow for the fact that x might be None. With
a ternary expression, you can write this:
print "x = " + x.getDisplayString() if x else "None"
But without a ternary expression, you need to do this instead:
if x:
xDisplay = x.getDisplayString()
else:
xDisplay = "None"
print "x = " + xDisplayString
Notice how one line became 5, and we had to create an auxiliary
variable. More powerful expressions make this very useful.
Similar examples could be found using a ternary expression in
lambda, in a list comprehension, and anywhere else that
expressions are used.
[2] It distinguishes choice from branching
If I have the following snippet of code:
if condition:
x = a
else:
x = b
then I think of it as doing one thing -- it sets x to one of
two different values. That is VERY different from this:
if condition:
x = a
else:
y = b
which I think of as doing one of TWO things -- either modifying
x or y. In the second case, I am doing what I think of mentally
as "branching", but in the first, I think of it (and speak of
when reading my code to another programmer) as just setting x
to one value or the other... a single action with no "branching"
(regardless of how the underlying machine implements it). Being
able to spell the first one as:
x = a if condition else b
makes something which is conceptually different LOOK different
-- and that's an important feature in a programming language.
(Consider reading Python vs reading Lisp.)
More information about the Python-list
mailing list