pythoncpyobject

Using Py_BuildValue() to create a list of tuples in C


I am trying to use Py_BuildValue() to create a list of tuples in C.

What I am trying to build would look like this:

[ (...), (...), ... ] 

I don't know the amount of tuples to create at compilation, so I can't use some static amount here.

Essentially using Py_BuildValue() with one tuple here is what it would look like for the code:

PyObject * Py_BuildValue("[(siis)]", name, num1, num2, summary);

But that would only be for one tuple. I need to have multiple tuples in the list that I could add via a for loop. How can I accomplish this?


Solution

  • You can use PyList_New(), PyTuple_New(), PyList_Append(), and PyTuple_SetItem() to accomplish this...

    const Py_ssize_t tuple_length = 4;
    const unsigned some_limit = 4;
    
    PyObject *my_list = PyList_New(0);
    if(my_list == NULL) {
        // ...
    }
    
    for(unsigned i = 0; i < some_limit; i++) {
        PyObject *the_tuple = PyTuple_New(tuple_length);
        if(the_tuple == NULL) {
            // ...
        }
    
        for(Py_ssize_t j = 0; i < tuple_length; i++) {
            PyObject *the_object = PyLong_FromSsize_t(i * tuple_length + j);
            if(the_object == NULL) {
                // ...
            }
    
            PyTuple_SET_ITEM(the_tuple, j, the_object);
        }
    
        if(PyList_Append(my_list, the_tuple) == -1) {
            // ...
        }
    }
    

    That will create a list of the form...

    [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11), (12, 13, 14, 15)]