PEP 308: A PEP Writer's Experience - PRO
Robin Munn
rmunn at pobox.com
Tue Feb 11 11:47:08 EST 2003
Paul Rubin <phr-n2003b at NOSPAMnightsong.com> wrote:
> 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
>
> which looks reasonable and might even pass the initial unit tests of a
> real program, but gives the wrong answer (zero) if x is 0 and y is
> negative. A conditional expression like
>
> x if (x > y) else y
>
> is much harder to get wrong.
There is a beautiful irony here: while demonstrating how easy it is to
get the "C and x or y" idiom wrong, you actually got it wrong. :-) You
wrote that:
x > y and x or y
gives the wrong answer (zero) if x is 0 and y is negative. Actually in
that case what you get is this:
x > y and x or y
(True) and 0 or (true value)
which evaluates to:
x or y
0 or (true value)
which evaluates to:
y
(true value)
So the result of the expression, in the case where x = 0 and y = -5,
say, is -5. But the expression was *supposed* to find the larger of x
and y, which would have been 0.
Yes, the "C and x or y" idiom is indeed far too confusing and should
therefore be avoided for practical use.
--
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838
More information about the Python-list
mailing list