[Python-Dev] PyObject_RichCompareBool identity shortcut

Hrvoje Niksic hrvoje.niksic at avl.com
Wed Apr 27 11:37:46 CEST 2011


The other day I was surprised to learn this:

 >>> nan = float('nan')
 >>> nan == nan
False
 >>> [nan] == [nan]
True                  # also True in tuples, dicts, etc.

# also:
 >>> l = [nan]
 >>> nan in l
True
 >>> l.index(nan)
0
 >>> l[0] == nan
False

The identity test is not in container comparators, but in 
PyObject_RichCompareBool:

     /* Quick result when objects are the same.
        Guarantees that identity implies equality. */
     if (v == w) {
         if (op == Py_EQ)
             return 1;
         else if (op == Py_NE)
             return 0;
     }

The guarantee referred to in the comment is not only (AFAICT) 
undocumented, but contradicts the documentation, which states that the 
result should be the "equivalent of o1 op o2".

Calling PyObject_RichCompareBool is inconsistent with calling 
PyObject_RichCompare and converting its result to bool manually, 
something that wrappers (C++) and generators (cython) might reasonably 
want to do themselves, for various reasons.

If this is considered a bug, I can open an issue.

Hrvoje


More information about the Python-Dev mailing list