PyObject_SetItem(..) *always* requires a Py_INCREF or not?

Tim Peters tim.peters at gmail.com
Sat Jun 17 15:02:11 EDT 2006


[seberino at spawar.navy.mil]
> I would think everytime you add an item to a list you must increase
> reference count of that item.

_Someone_ needs to.  When the function called to add the item does the
incref itself, then it would be wrong for the caller to also incref
the item.

> http://docs.python.org/api/refcountDetails.html has an example that
> seems to contradict that....
>
> int
> set_all(PyObject *target, PyObject *item)
> {
>     int i, n;
>
>     n = PyObject_Length(target);
>     if (n < 0)
>         return -1;
>     for (i = 0; i < n; i++) {
>         if (PyObject_SetItem(target, i, item) < 0)
>             return -1;
>     }
>     return 0;
> }
>
> *WHY* don't you need a Py_INCREF(item); in the for loop!?!?!?

You should take a break, and read that section again later ;-)

The _point_ of that example is in fact to illustrate that you don't
need to incref when calling PyObject_SetItem().  While I can't know,
I'm guessing that you're still "seeing" PyList_SetItem() here, which
has radically different behavior.  PyList_SetItem() steals a reference
to its second argument, but PyObject_SetItem() does not.  Read the
whole section again from its start, and this should be much clearer
the second time through.



More information about the Python-list mailing list