[Pyrex] [Pyrex, Cython]Subclass basic exceptions inside Pyrex

Greg Ewing greg.ewing at canterbury.ac.nz
Tue Feb 23 05:13:44 CET 2010


Daniele Pianu wrote:

>       cdef extern class __builtin__.Exception [object PyExc_Exception]:
>         pass
>       cdef class MyPyrexException( Exception ):
>         pass

Sorry it's taken a while, Daniele, but I've just got around
to investigating this.

It turns out there are several things wrong with the above
code:

1) PyExc_Exception is a pointer to the exception type object,
not the name of the struct used for its instances. The name
you need to use here is PyBaseExceptionObject. (There is no
struct declared specifically for Exception, but it's derived
from BaseException and doesn't extend it with any more struct
members, so this is good enough.)

2) PyBaseExceptionObject is declared in the header file using
a typedef, so you need to prefix the external class declaration
with 'ctypedef'.

3) You need to put the declaration in a 'cdef extern from'
block so that Pyrex doesn't emit a struct declaration of its
own for it (which wouldn't be correct, since Pyrex doesn't
know what it contains).

Putting all this together, the following compiles and imports
okay for me using Pyrex:

   cdef extern from *:
     ctypedef class __builtin__.Exception [object PyBaseExceptionObject]:
       pass

   cdef class MyPyrexException(Exception):
     pass

However, having said all that, I should point out that using
an extension type for an exception is probably overkill, and
you're probably just as well off using a normal Python subclass.

-- 
Greg



More information about the Pyrex mailing list