PyList_SetItem vs. PyList_SETITEM
Asked Answered
R

1

9

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?

Rounded answered 24/4, 2012 at 20:12 Comment(0)
R
9

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 ith 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 ith 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.

Rebus answered 24/4, 2012 at 20:43 Comment(3)
But will I get into any sort of trouble if I use PyList_SetItem all the time and never use PyList_SETITEM?Rounded
Absolutely not. In fact, that's probably the safest way. PyList_SET_ITEM is mostly a speed hack.Rebus
Thanks - and thanks for adding the clarifying last line to your original answer.Rounded

© 2022 - 2024 — McMap. All rights reserved.