Problem slicing a list with the C API

Jen Kris jenkris at tutanota.com
Sat Mar 12 16:24:09 EST 2022


I have a C API project where I have to slice a list into two parts.   Unfortunately the documentation on the slice objects is not clear enough for me to understand how to do this, and I haven’t found enough useful info through research.  The list contains tuple records where each tuple consists of a dictionary object and a string.  

The relevant part of the Python code is:

half_slice = int(len(dictdata) * 0.5)
subdata_a = dictdata[half_slice:]
subdata_b = dictdata[:half_slice]

This is what I’ve done so far with the C API:

int64_t Calc_Slices(PyObject* pDictdata, int64_t records_count)
{
long round_half = records_count * 0.5;
PyObject* half_slice = PyLong_FromLong(round_half);

PyObject* slice = PySlice_New(PyLong_FromLong(0), half_slice, 0);
PyObject* subdata_a = PyObject_GetItem(pDictddata, slice);

return 0;
}

On the final line (subdata_a) I get a segfault.  I know that the second parameter of  PyObject_GetItem is a “key” and I suspect that’s where the problem comes from, but I don’t understand what a key is in this context. 

The code shown above omits error handling but none of the objects leading up to the final line is null, they all succeed. 

Thanks for any ideas.

Jen



More information about the Python-list mailing list