From what I can tell, the difference between PyList_SetItem and PyList_SETITEM is that PyList_SetItem will lower the reference count of the list item it overwrites and PyList_SETITEM does not.
Is there any reason why I shouldn't just use PyList_SetItem all the time? Or would I get into trouble if I used PyList_SetItem to initialize an index position in a list?
PyList_SET_ITEM
is an unsafe macro that basically sticks an object into the list's internal pointer array without any bound checks. If anything non-NULL
is in the i
th position of the list, a reference leak will occur. PyList_SET_ITEM
steals the reference to the object you put in the list. PyList_SetItem
also steals the reference, but it checks bounds and decrefs anything which may be in the i
th position. The rule-of-thumb is use PyList_SET_ITEM
to initialize lists you've just created and PyList_SetItem
otherwise. It's also completely safe to use PyList_SetItem
everywhere; PyList_SET_ITEM
is basically a speed hack.
来源:https://stackoverflow.com/questions/10305327/pylist-setitem-vs-pylist-setitem