Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/ext/notes/lenard_lindstrom-richcmp.txt
4108 views
1
Apparently an extension type subclass will only inherit its base
2
class rich comparison function if the subclass does not define a hash
3
function. This is a CPython thing that has nothing to do with Pyrex.
4
I had to look at the Python interpreter source code to discover what
5
was happening.
6
7
Two other things. First it is dangerous to cast an object pointer to
8
something else. No type checking is done by Pyrex so this could lead
9
to incorrect memory accesses. Second, if your type does not support a
10
particular kind of comparison then __richcmp__ should return
11
NotImplemented, a builtin object. This lets Python try other
12
comparisons. So your comparison function should look like something
13
like this:
14
15
def __richcmp__(x, y, case):
16
print "__richcmp__"
17
cdef Base self, other
18
try:
19
self = x
20
other = y
21
if case == 2:
22
return bool(self.a == other.a)
23
except TypeError:
24
pass
25
return NotImplemented
26
27
Of cource you might also want to implement != as well.
28
29
Lenard Lindstrom
30
<[email protected]>
31