[Python-ideas] checking for identity before comparing built-in objects

Guido van Rossum guido at python.org
Tue Oct 9 02:11:33 CEST 2012


On Mon, Oct 8, 2012 at 5:02 PM, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> Guido van Rossum wrote:
>
>> It's not about equality. If you ask whether two NaNs are *unequal* the
>> answer is *also* False.
>
>
> That's the weirdest part about this whole business, I think.
> Unless you're really keeping your wits about you, it's easy
> to forget that the assumption (x == y) == False implies
> (x != y) == True doesn't necessarily hold.
>
> This is actually a very important assumption when it comes
> to reasoning about programs -- even more important than
> reflexivity, etc, I believe. Consider
>
>    if x == y:
>       dosomething()
>    else:
>       dosomethingelse()
>
> where x and y are known to be floats. It's easy to see that
> the following is equivalent:
>
>    if not x == y:
>       dosomethingelse()
>    else:
>       dosomething()
>
> but it's not quite so easy to spot that the following is
> *not* equivalent:
>
>    if x != y:
>       dosomethingelse()
>    else:
>       dosomething()
>
> This trap is made all the easier to fall into because float
> comparison is *mostly* well-behaved, except for a small subset
> of the possible values. Most other nonstandard comparison behaviours
> in Python apply to whole types. E.g. we refuse to compare complex
> numbers for ordering, even if their values happen to be real,
> so if you try that you get an early exception. But the weirdness
> with NaNs only shows up in corner cases that may escape testing.
>
> Now, there *is* a third possibility -- we could raise an exception
> if a comparison involving NaNs is attempted. This would be a
> more faithful way of adhering to the IEEE 754 specification that
> NaNs are "unordered". More importantly, it would make the second code
> transformation above valid in all cases.
>
> So the question that really needs to be answered, I think, is
> not "Why is NaN == NaN false?", but "Why doesn't NaN == anything
> raise an exception, when it would make so much more sense to
> do so?"

Because == raising an exception is really unpleasant. We had this in
Python 2 for unicode/str comparisons and it was very awkward.

Nobody arguing against the status quo seems to care at all about
numerical algorithms though. I propose that you go find some numerical
mathematicians and ask them.

-- 
--Guido van Rossum (python.org/~guido)



More information about the Python-ideas mailing list