[Pyrex] BUG: a problem with type casting in __richcmp__...

Greg Ewing greg at cosc.canterbury.ac.nz
Fri May 23 01:18:15 CEST 2003


Alexander A Naanou <alex_nanou at pochtamt.ru> wrote:

> cdef public class callproxy:
>   cdef obj
> 
>   def __richcmp__(self, other, int op):
>     cdef callproxy tmp
>     if type(other) == callproxy:
>       tmp = other
>       # ...
>       return self.obj.__cmp__(tmp.obj)
> 
> what happend is in the line "return self.obj.__cmp__(tmp.obj)" 
> we got a python (e.g. indirect) lookup

Read the section on "Arithmetic Methods" in the "Special Methods
of Extension Types" page of the Language Overview. What it says
there applies to the __richcmp__ method (as you'll see if you
look at the signature of __richcmp__ in the special method table).

Briefly, the first argument of __richcmp__ is not necessarily
"self", and Pyrex doesn't assume that it's any particular type.
You need to type test and convert *both* operands, e.g.

  def __richcmp__(x, y, int op):
    cdef callproxy self, other
    if isinstance(x, callproxy):
      self = x
      if isinstance(y, callproxy):
        other = y
        return self.obj.__cmp__(other.obj)

By the way, you'll notice I've used isinstance() instead of
comparing types, which is the preferred way now that
built-in types are subclassable.

Greg Ewing, Computer Science Dept, +--------------------------------------+
University of Canterbury,	   | A citizen of NewZealandCorp, a	  |
Christchurch, New Zealand	   | wholly-owned subsidiary of USA Inc.  |
greg at cosc.canterbury.ac.nz	   +--------------------------------------+




More information about the Pyrex mailing list