Reputation: 3059
My C-application is loading the python interpreter dll and calling the function list = PyList_New(len)
to create a new python list of 'len' size.
Two questions:
1. What happens if I call PyList_Append(list, item)
more than len
times? I assume it should throw an exception. Is my understanding correct?
2. More importantly, my second question is whether there is a way to resize the list? I looked at the C APIs at: https://docs.python.org/2/c-api/list.html#c.PyList_SetItem, but could not find such an API. Any suggestions/comments/workaround?
The context of my question is that I need to create the list much earlier than when the list items and the count of them is known.
Upvotes: 2
Views: 311
Reputation: 30936
PyList_New
creates a list filled with NULL
pointers. You're supposed to set all of those pointers using PyList_SetItem
before sending the list back to Python or calling any Python functions on it.
PyList_Append
(and PyList_Insert
) are really just equivalent to calling somelist.append
(and somelist.insert
) from Python. They resize the list for you. I'm not 100% sure if they account any NULL
elements, so it's probably best not to call them on a list that you've made from PyList_New
and that you haven't completely filled yet. What you're doing (allocating a list with some NULL
pointers then appending it) is definitely wrong since the NULL
pointers are never filled in. Instead you should just be using PyList_Append
and PyList_Insert
on a list built from empty. You could also call list.extend
to add multiple elements to the list at once - there is no direct access to that through the C API but you can call it through PyObject_CallMethodObjArgs
or similar.
Internally the list allocates more space than it needs to it only has to reallocate occasionally. There's no way for you to control this.
Upvotes: 0