PEP 308: A PEP Writer's Experience - PRO
adalke at mindspring.com
Sun Feb 9 01:24:12 CET 2003
> 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:
Or do what's often done and write a dummy display
used for the null case.
This is very nice because there are no branches in the
code flow, except once at the very top. And the fewer
branches the better.
> Similar examples could be found using a ternary expression in
> lambda, in a list comprehension, and anywhere else that
> expressions are used.
I just posted a really hairy list comp w/ if/else expression.
It looks like
indicies = [(long_function_name(atom->realAtom(), atomCount,
if atom != OXYGEN else -1)
for atom in (atom1, atom2, atom3, atom4)]
Given the code base from which I extracted it, it is
likely that the programmers would have thought about this
sort of construct, and deemed it 'cool'.
I would prefer
indicies = 
for atom in (atom1, atom2, atom3, atom4):
if atom != OXYGEN:
In the analysis from which this came, I estimated that, in my target
user base, the ?: would be used appropriately about once every
2,000 lines of Python code, and likely to use it inappropriately at
a more frequent rate than that.
> 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.
Good point. Still, I think (and I now have the numbers to back me
up) that amount non-expert developers the misuse rate is
higher than the proper use rate and that in any case the use
rate is very low -- too low to warrant a fundamental/low-level
construct like this which introduces a choice with no good,
unambiguous guidelines of when it is proper use.
(See my post with the buy/bonus buy/werewolf buy for just
such an example.)
dalke at dalkescientific.com
More information about the Python-list