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

Steven D'Aprano steve at pearwood.info
Wed Oct 10 03:14:26 CEST 2012


On 10/10/12 09:13, Joshua Landau wrote:
> Just a curiosity here (as I can guess of plausible reasons myself, so there
> probably are some official stances).
>
> Is there a reason NaNs are not instances of NaN class?

Because that would complicate Python's using floats for absolutely no benefit.
Instead of float operations always returning a float, they would have to return
a float or a NAN. To check for a valid floating point instance, instead of
saying:

isinstance(x, float)

you would have to say:

isinstance(x, (float, NAN))

And what about infinities, denorm numbers, and negative zero? Do they get
dedicated classes too?

And what is the point of this added complexity? Nothing.

You *still* have the rule that "x == x for all x, except for NANs". The
only difference is that "NANs" now means "instances of NAN class" rather than
"NAN floats" (and Decimals). Working with IEEE 754 floats is now far more of
a nuisance because some valid floating point values aren't floats but have a
different class, but nothing meaningful is different.


> Then x == x would be True (as they want), but [this NaN] == [that NaN]
> would be False, as expected.

Making NANs their own class wouldn't give you that. If we wanted that
behaviour, we could have it without introducing a NAN class: just change the
list __eq__ method to scan the list for a NAN using math.isnan before checking
whether the lists were identical.

But that would defeat the purpose of the identity check (an optimization to
avoid scanning the list)! Replacing math.isnan with isinstance doesn't change
that.


> I guess that raises the question about why x == x but sqrt(-1) != sqrt(-1),

That question has already been raised, and answered, repeatedly in this thread.


> but it seems a lot less of a big deal than all of the exceptions with
> container equalities.

Container equalities are not a big deal. I'm not sure what problem you think
you are solving.



-- 
Steven



More information about the Python-ideas mailing list