how to read a list from python in C?

skip at pobox.com skip at pobox.com
Fri May 19 13:39:08 EDT 2006


    lialie> The list has a random length.
    lialie> Do you mean to do it in this way?
    lialie> use PyTuple_Size(args), in a loop
    lialie> use PyTuple_GetItem(args, i) 
    lialie> or
    lialie> use PyArg_VaParse?

Sketch (that means off-the-top-of-my-head, untested,  99.9% guaranteed
incorrect in some fashion):

    static PyObject *
    my_list_method(PyObject *self, PyObject *args) {
        PyListObject *list = NULL;
        PyTupleObject *point = NULL;
        int list_len;
        double *points = NULL;
        double x, y;

        if (PyArg_ParseTuple(args, "O!", &PyList_Type, &list) == NULL)
            return NULL;

        list_len = PyList_GetSize(list);
        points = PyMem_Alloc(list_len * 2 * sizeof(double));
        if (points == NULL)
            goto fail;

        for (i = 0; i < list_len; i++) {
            point = PyList_GetItem(list, i)
            if (point == NULL || !PyTuple_Check(point))
                goto fail;
            if (Py_ArgParseTuple(point, "(dd)", &x, &y) == NULL)
                goto fail;
            Py_DECREF(point);
            points[i*2] = x;
            points[i*2+1] = y;

        /* do your thing with your list of floats here */
        ...

        PyMem_Free(points);
        Py_DECREF(list);

        Py_INCREF(None);           /* or whatever makes sense */
        return None;

fail:
        Py_XDECREF(list);
        Py_XDECREF(point);
        if (points != NULL)
            PyMem_Free(points);
        return NULL;
}

        



More information about the Python-list mailing list