PEP 308: A PEP Writer's Experience - PRO

Brian McErlean b_mcerlean at yahoo.com
Sun Feb 9 17:44:00 EST 2003


Paul Rubin <phr-n2003b at NOSPAMnightsong.com> wrote in message news:<7xisvusbp8.fsf at ruckus.brouhaha.com>...
> Michael Chermside <mcherm at destiny.com> writes:
> > 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.
> > [2] It distinguishes choice from branching
> 
> I think Andrew Koenig pointed out a third argument which many of us
> had perhaps underestimated: it can prevent bugs.  A lot of the
> workarounds attempted for its absence are flat out wrong.  He gives an
> example showing finding the maximum of x and y with
> 
>    x > y and x or y

Yes, but this is really a strawman.  To be fair, you should argue
against the "right" way of doing this, which (other than the trivial
max() for this example) is:

if x > y:
    result = x
else:
    result = y

which is more longwinded, but saving characters was never really
python's goal.  I think people are aware of the problem you mention,
hence the clumsy, but correct "(x > y and [x] or [y])[0]" methods.
However, I hope that either of these two "clever" methods would never
be actually used in production code - the real alternative you have
to argue against is the one above.

I think, however that you can still argue against it from a bug
reduction standpoint - what if the actual result you want is
something like:

self.long_varname[i].value = x if x>y else y
or:
    self.do_something_with(x if x>y else y)

ie. what you do with the result is more than a trivial variable
assignment.  In this case, you have the real issue of duplicated
code, that you need to check for all paths, and keep in sync.
eg.

if something_unusual_happened():
    self.lnog_varname[i].value = x
else:
    self.long_varname[i].value = y

is an error that may not be apparent if something_unusual_happened()
is an event that would rarely trigger.

I think I'm pretty neutral on the idea though.  I can see the why
people want it, but I think the solution is really ugly (though
nicer than any of the alternative spelling I've seen), and I've never
really come across a compelling need for it.  For anything more
complicated than a binary choice, my favourate method is dispatching
on a dictionary, and for simple stuff, I'm not particularly bothered
by the more verbose methods we already have.  I think I'd prefer to
read ternary operator syntax than and/or abuse though.

Brian.




More information about the Python-list mailing list