Skip to content

Python/C Inconsistency: Detecting classes that just implement __eq__ #165

@jamadden

Description

@jamadden

Consider:

from BTrees import family64

class WithEq(object):
    def __eq__(self, other):
        return NotImplemented

s = family64.OO.TreeSet()
s.add(WithEq())

The WithEq class has default comparison: it doesn't define any sorting methods.

The C implementation doesn't detect this (because just defining __eq__ is enough to fill in the tp_richcompare slot):

$ python /tmp/foo.py
$

The Python implementation does detect this:

$ PURE_PYTHON=1 python /tmp/foo.py
Traceback (most recent call last):
  File "/tmp/foo.py", line 7, in <module>
    s.add(WithEq())
  File "//BTrees/src/BTrees/_base.py", line 1406, in add
    return self._set(self._to_key(key))[0]
  File "//BTrees/src/BTrees/_datatypes.py", line 255, in __call__
    raise TypeError("Object of class %s has default comparison" % (type(item).__name__,))
TypeError: Object of class WithEq has default comparison

Can we improve the C implementation?

#ifdef PY3K
if (Py_TYPE(arg)->tp_richcompare == Py_TYPE(object_)->tp_richcompare)
#else
if ((Py_TYPE(arg)->tp_richcompare == NULL
&& Py_TYPE(arg)->tp_compare == Py_TYPE(object_)->tp_compare)
/* Also exclude new-style classes. On Python 2, they can be compared,
but order by address, making them not suitable for BTrees. */
|| PyType_CheckExact(arg)
/* But let classes with a meta class that implements comparison through. */
|| (PyType_Check(arg) && Py_TYPE(arg)->tp_richcompare == PyType_Type.tp_richcompare)
)

A real-world class that demonstrates this is persistent.wref.WeakRef.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions