Idiom for error checking within a C extension

J

Jon Perez

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

David M. Cooke

At some point said:
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().
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,040
Latest member
papereejit

Latest Threads

Top