writing a C function to manipulate python lists
Fredrik Lundh
fredrik at pythonware.com
Thu Mar 1 13:40:36 EST 2001
Michael Vanier wrote:
> I've been programming in python for many years but have never had to solve
> this particular problem. I would like to write a short C function that will
> be part of a python-callable module. The function will receive two python
> lists as arguments. Currently I do this in python, but my code uses this
> function very heavily and it's the major speed bottleneck in the code. The
> hope is that the C function will be much faster than iterating through the
> lists in python (which may not be true, but I'd like to see for myself).
>
> If anyone has some code lying around that does something like this, could
> they pass it on to me?
there's plenty of code in the Python source distribution...
searching for PyList and/or PySequence should help. here's
one example, based on SRE's compile function:
static PyObject *
myfunc(PyObject* self_, PyObject* args)
{
int i, n;
/* accept a single list object */
PyObject* code;
if (!PyArg_ParseTuple(args, "O!", &PyList_Type, &code)
return NULL;
/* get the size */
n = PyList_GET_SIZE(code);
/* loop over the members */
for (i = 0; i < n; i++) {
int v;
PyObject *o = PyList_GET_ITEM(code, i);
v = PyInt_AsLong(o);
if (v == -1 && PyErr_Occurred())
goto oops; /* not a number */
printf("%d\n", v);
}
...
}
to handle any kind of sequence, use the PySequence abstract
API instead of the PyList API.
Cheers /F
More information about the Python-list
mailing list