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

S

seberino

I would think everytime you add an item to a list you must increase
reference count of that
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!?!?!?

Thanks!

Chris
 
T

Tim Peters

[[email protected]]
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.
 
K

K.S.Sreeram

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!?!?!?

Thats because PyObject_SetItem automatically increases the refcount of
the 'item' that you pass. Whereas, PyTuple_SetItem and PyList_SetItem
*DONT* automatically increment the refcount.

Sreeram


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFElFNBrgn0plK5qqURAj7gAJwO/1i1gcenS7Ng3nSIHCwGopsmigCgon+0
RAWiMsubSTK10Qu6LhS74Hk=
=Mrg3
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top