[Pyrex] Re: __richcmp__ , __hash__: dependencies on subclassing ?

Uwe Hoffmann qual at tiscali.de
Mon Jan 30 22:53:09 CET 2006


Lenard Lindstrom schrieb:
> Apparently an extension type subclass will only inherit its base 
> class rich comparison function if the subclass does not define a hash 
> function. This is a CPython thing that has nothing to do with Pyrex. 
> I had to look at the Python interpreter source code to discover what 
> was happening.
>
hmm, that probably means code must be duplicated, but it is a
cpython feature then.

> Two other things. First it is dangerous to cast an object pointer to 
> something else. No type checking is done by Pyrex so this could lead 
> to incorrect memory accesses. 
after looking at the generated c source of my original and your changed
example it's now clear what's the difference between the statements. It 
wasn't clear to me what "cdef Base self ; self=x;" actually means (on 
C-level).
I had some isinstance checks before the cast but PyObject_TypeCheck is
obviously better.
 > Second, if your type does not support a
> particular kind of comparison then __richcmp__ should return 
> NotImplemented, a builtin object. This lets Python try other 
> comparisons. 
it was just a stripped  down example (which promptly suffered the
self <--> left  typo).
So your comparison function should look like something
> like this:

>       def __richcmp__(x, y, case):
>           print "__richcmp__"
>           cdef Base self, other
>           try:
>               self = x
>               other = y
>               if case == 2:
>                   return bool(self.a == other.a)
>           except TypeError:
>               pass
>           return NotImplemented
> 
> Of cource you might also want to implement != as well.
> 
> Lenard Lindstrom
> <len-l at telus.net>

Thany you

Uwe Hoffmann




More information about the Pyrex mailing list