float("nan") in set or as key

Raymond Hettinger python at rcn.com
Mon May 30 00:49:14 EDT 2011


On May 28, 4:41 pm, MRAB <pyt... at mrabarnett.plus.com> wrote:
> Here's a curiosity. float("nan") can occur multiple times in a set or as
> a key in a dict:

Which is by design.

NaNs intentionally have multiple possible instances (some
implementations even include distinct payload values).

Sets and dicts intentionally recognize an instance as being equal to
itself (identity-implies-equality); otherwise, you could put a NaN in
a set/dict but not be able to retrieve it.  Basic invariants would
fail -- such as:  assert all(elem in container for elem in container).

The interesting thing is that people experimenting with exotic objects
(things with random hash functions, things with unusual equality or
ordering relations, etc) are "surprised" when those objects display
their exotic behaviors.

To me, the "NaN curiousities" are among the least interesting.  It's
more fun to break sort algorithms with sets (which override the
ordering relations with subset/superset relations) or with an object
that mutates a list during the sort.  Now, that is curious :-)

Also, Dr Mertz wrote a Charming Python article full of these
curiosities:
http://gnosis.cx/publish/programming/charming_python_b25.txt

IMO, equality and ordering are somewhat fundamental concepts.  If a
class is written that twists those concepts around a bit, then it
should be no surprise if curious behavior emerges.  Heck, I would
venture to guess that something as simple as assuming the speed of
light is constant might yield twin paradoxes and other
curiousities ;-)

Raymond



More information about the Python-list mailing list