Type checking inside a C extension

Jon Perez jbperez808 at yahoo.com
Sun Apr 4 21:47:53 EDT 2004


I have a C extension function into which I pass a list of lists
of tuples:

[
   [ ("A",1), ("B",2) ("C",3) ],
   [ ("A",1), ("B",2) ("C",3) ],
   [ ("A",1), ("B",2) ("C",3) ],
]

I then unpack the values (down to the tuple elements) into their C
values using:

   PyLong_AsLong(PyTuple_GetItem(tupl,0))

to extract the int from the first element of the tuple and

   PyString_AsString(PyTuple_GetItem(tupl,1))[0]

to get the char from the second element.


The problem is that neither PyLong_AsLong() nor PyString_AsString()
does any type checking so the interpreter crashes when I try to use
the values returned by PyLong_AsLong() and PyString_AsString() if
they happen to be fed objects - the tuple elements in this case - of
the wrong type.

I could certainly do a type check using PyLong_Check() and
PyString_Check() on the tuple items and raise a TypeError exception
to avoid leading to a crash, but I am concerned about the speed hit
as this is the innermost loop of a routine which gets called
really often (I use it for text block transfers).

Is there a less expensive way to check the type, or somehow
avoid a crashing situation (i.e. an exception gets properly raised)
without calling PyLong_Check() and PyString_Check() the elements
of each and every tuple?



More information about the Python-list mailing list