float("nan") in set or as key
Carl Banks
pavlovevidence at gmail.com
Sun May 29 21:07:50 EDT 2011
On Sunday, May 29, 2011 7:41:13 AM UTC-7, Grant Edwards wrote:
> It treats them as identical (not sure if that's the right word). The
> implementation is checking for ( A is B or A == B ). Presumably, the
> assumpting being that all objects are equal to themselves. That
> assumption is not true for NaN objects, so the buggy behavior is
> observed.
Python makes this assumption in lots of common situations (apparently in an implementation-defined manner):
>>> nan = float("nan")
>>> nan == nan
False
>>> [nan] == [nan]
True
Therefore, I'd recommend never to rely on NaN != NaN except in casual throwaway code. It's too easy to forget that it will stop working when you throw an item into a list or tuple. There's a function, math.isnan(), that should be the One Obvious Way to test for NaN. NaN should also never be used as a dictionary key or in a set (of course).
If it weren't for compatibility with IEEE, there would be no sane argument that defining an object that is not equal to itself isn't a bug. But because there's a lot of code out there that depends on NaN != NaN, Python has to tolerate it.
Carl Banks
More information about the Python-list
mailing list