[capi-sig] How to manipulate C table as python list ?
Stefan Behnel
python_capi at behnel.de
Sun Jan 18 17:18:41 CET 2009
Hrvoje Niksic wrote:
> PyObject *sum(PyObject *ignored, PyObject *lst)
> {
> int i, s = 0;
> if (!PyList_Check(lst)) {
> PyErr_Format(PyExc_TypeError, "sum: expected list, got %s",
> lst->ob_type->tp_name);
> return NULL;
> }
> for (i = 0; i < PyList_GET_SIZE(lst); i++) {
> ... sum the list ...
> return PyInt_FromLong(s);
> }
>
>> My question is:
>> which option should I use with PyArg_ParseTuple?
>
> If your function is declared to take one argument with METH_O, you
> don't need PyArg_ParseTuple at all. If it's declared to take a
> variable number of arguments, you'd use it like this:
>
> PyObject *sum(PyObject *ignored, PyObject *args)
> {
> int i, s = 0;
> PyObject *lst;
> if (!PyArg_ParseTuple(args, "O", &lst))
> return NULL;
> ...
> }
You can also write your code in Cython. The following Cython code will
generate roughly the same C code that you present above:
def sum(list l):
cdef int i, s = 0
for i in l:
s += i
return s
http://cython.org/
Stefan
More information about the capi-sig
mailing list