Idiom for error checking within a C extension

Jon Perez jbperez808 at yahoo.com
Wed Apr 7 03:43:31 EDT 2004


I want to retrieve a value from a tuple and convert it to a C
type.  Is the following idiom okay?

   if (!(
         ( tmp_pyobj=PyTuple_GetItem(tuple,1) ) &&
         ( c_int=PyInt_AsLong(tmp_pyobj) )
      ))
     {
       if (PyErr_ExceptionMatches(PyExc_TypeError))
         PyErr_SetString(PyExc_TypeError,"tuple's 1st member was not an integer");
       return NULL;
     }


The PyErr_ExceptionMatches/PyErr_SetString combination in the if-block is
where I'm a bit unsure.  I want to check if the tuple element is of the
correct type (a PyInt in this case) and if it isn't, I want to return my
own customized error message instead of the default TypeError message.
I'm kind of uncomfortable with the idea that I am checking for the kind
of exception raised and then afterwards calling a function which can
change it (even if I don't really end up doing that).



More information about the Python-list mailing list