float("nan") in set or as key

Gregory Ewing greg.ewing at canterbury.ac.nz
Sat May 28 21:04:32 EDT 2011


MRAB wrote:
> float("nan") can occur multiple times in a set or as 
> a key in a dict:
> 
>  >>> {float("nan"), float("nan")}
> {nan, nan}
> 
> except that sometimes it can't:
> 
>  >>> nan = float("nan")
>  >>> {nan, nan}
> {nan}

NaNs are weird. They're not equal to themselves:

Python 2.7 (r27:82500, Oct 15 2010, 21:14:33)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
 >>> nan = float("nan")
 >>> nan == nan
False

This confuses the daylights out of Python's dict lookup machinery,
which assumes that two references to the same object can't possibly
compare unequal, so it doesn't bother calling __eq__ on them.

-- 
Greg



More information about the Python-list mailing list