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

Lenard Lindstrom len-l at telus.net
Mon Jan 30 01:10:53 CET 2006


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.

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. 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. 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>

On 29 Jan 2006 at 17:01, Uwe Hoffmann wrote:

> Uwe Hoffmann schrieb:
> 
> >      def __richcmp__(self,other,case):
> >          print "__richcmp__"
> >          if case == 2:
> >              return bool((<Base>left).a == (<Base>right).a)
> 
> oh man. read
> 		return bool((<Base>self).a == (<Base>other).a)
> 
> 
> _______________________________________________
> Pyrex mailing list
> Pyrex at lists.copyleft.no
> http://lists.copyleft.no/mailman/listinfo/pyrex
> 





More information about the Pyrex mailing list