By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,547 Members | 1,435 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,547 IT Pros & Developers. It's quick & easy.

Idiom for error checking within a C extension

P: n/a
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).
Jul 18 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
At some point, Jon Perez <jb********@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
Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.