Idiom for error checking within a C extension

David M. Cooke cookedm+news at physics.mcmaster.ca
Wed Apr 7 16:45:25 EDT 2004


At some point, Jon Perez <jbperez808 at yahoo.com> wrote:

> 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) ) &&

You've got 1 here, but mention the first member below (that's number 0).

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

That's no different than the python code

try:
    p = tple[0]
    c = int(p)
except TypeError:
    raise TypeError("tuple's 1st member was not an integer")

You could use PyInt_Check(), and throw your own error, but if you want
to handle longs or things that can be coerced to ints, you end up
rewriting PyInt_AsLong().

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca



More information about the Python-list mailing list