Problem slicing a list with the C API

Jen Kris jenkris at tutanota.com
Sat Mar 12 16:52:48 EST 2022


Thanks to you both.  I am going to implement PySequence_Get_Slice now.  If I have trouble then, per comments from Chris Angelico, I will iterate through pDictData to verify it because I haven't done that.  It is not null, however.  

 Jen


Mar 12, 2022, 13:40 by python at mrabarnett.plus.com:

> On 2022-03-12 21:24, Jen Kris via Python-list wrote:
>
>> 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.
>>
> Use PySequence_GetSlice to slice the list.
>
> Also, why use floats when you can use integers?
>
>  long round_half = records_count / 2;
>
> (In Python that would be half_slice = len(dictdata) // 2.)
> -- 
> https://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list