Q: Raising exceptions from extension modules

Pearu Peterson pearu at cens.ioc.ee
Sat Aug 10 05:47:23 EDT 2002


Hi,

Q: how to raise an exception from a function defined in an extension
module such that the name of the C function will show up also in the
traceback message?

To make myself clear, let me illustrate my question with the following 
example:

1) pure python function:

>>> def foo(): raise RuntimeError, 'hello!'
... 
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 1, in foo
RuntimeError: hello!
>>> 

2) equivalent function from a Python extension module gives:

>>> import t
>>> t.foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
RuntimeError: hello!

where

/*************** module t.c **************/
#include <Python.h>
static PyObject * foo(PyObject* self, PyObject* args)
{
  if (!PyArg_ParseTuple(args, "")) return NULL;
  PyErr_SetString(PyExc_RuntimeError,"hello!");
  return NULL;
}
static PyMethodDef TMethods[] = {
  {"foo",  foo, METH_VARARGS},  
  {NULL, NULL, 0, NULL}        /* Sentinel */
};
void initt(void) {
  (void) Py_InitModule("t", TMethods);
}
/************** eof t.c *******************/

The question is: what should be done in the C function foo(..)
so that the traceback message would be "identical" to the one from the 
pure python function foo()? Identical in the sense that the traceback
should include a line containing some reference to a C function foo.

Is it possible? I am using Python versions 2.1 and 2.2.
Are there other ways to track down exception paths in extension modules?

Thanks,
	Pearu





More information about the Python-list mailing list