[Python-Dev] PyObject_RichCompareBool identity shortcut

Raymond Hettinger raymond.hettinger at gmail.com
Wed Apr 27 16:39:49 CEST 2011


On Apr 27, 2011, at 2:37 AM, Hrvoje Niksic wrote:

> The other day I was surprised to learn this:
> 
> >>> nan = float('nan')
> >>> nan == nan
> False
> >>> [nan] == [nan]
> True                  # also True in tuples, dicts, etc.

Would also be surprised if you put an object in a dictionary but couldn't get it out?  Or added it to a list but its count was zero?

Identity-implies-equality is necessary so that classes can maintain their invariants and so that programmers can reason about their code.  It is not just in PyObject_RichCompareBool, it is deeply embedded in the language (the logic inside dicts for example).  It is not a short-cut, it is a way of making sure that internally we can count on equality relations reflexive, symmetric, and transitive.  A programmer needs to be able to make basic deductions such as the relationship between the two forms of the in-operator:   for elem in somelist:  assert elem in somelist  # this should never fail.

What surprises me is that anyone gets surprised by anything when experimenting with an object that isn't equal to itself.  It is roughly in the same category as creating a __hash__ that has no relationship to __eq__ or making self-referencing sets or setting False,True=1,0 in python 2.  See http://bertrandmeyer.com/2010/02/06/reflexivity-and-other-pillars-of-civilization/ for a nice blog post on the subject.


Raymond



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20110427/efa56ed3/attachment.html>


More information about the Python-Dev mailing list