[Pyrex] Return value problems

Greg Ewing greg.ewing at canterbury.ac.nz
Tue May 29 01:49:55 UTC 2007


Georg Grabler wrote:

> cdef class config:
>   ...
>   cdef char* xyz
> 
> cdef getXYZ(self)
>   return self.xyz

I'm assuming this is meant to be a method of class config
(to work as a stand-alone function, a type declaration
would be needed for the parameter).

> if (config.getXYZ() == NULL):

This test makes no sense. The way your getXYZ method
is defined (whether the def or cdef version) it's returning
a Python object, which will never be NULL.

Moreover, if xyz is ever NULL, Python will crash trying
to construct a Python string from it before even getting
to your test.

The way to proceed depends on whether getXYZ needs to be
callable from Python. If it will only ever be called from
Pyrex code, you could make it a C method that returns a
char *, i.e.

   cdef class config:
     ...
     cdef char *getXYZ(self):
       return self.xyz

Then you can do 'if foo.getXYZ() == NULL'. However, since
you need to know that you have an object of class config
before you can call the method, there's not much point in
having the method rather than just accessing the xyz
attribute directly.

If the method needs to be callable from Python, you will
need to declare it with def, and it will need to return a
Python string. If xyz can be NULL, you will need to test
for this and return something appropriate, e.g.

   cdef class config:
     ...
     def getXYZ(self):
       if self.xyz <> NULL:
         return self.xyz
       else:
         return None

Then you can do things like

   if foo.getXYZ() is None:
     ...

--
Greg



More information about the Pyrex mailing list