Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
jamadden opened this issue Apr 21, 2021 · 0 comments
Open

Comments

@jamadden
Copy link
Member

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant