[capi-sig] DECREF when using PyDict_SetItem...

Hrvoje Niksic hniksic at xemacs.org
Fri Jul 2 12:02:38 CEST 2010


Tim Golden <mail at timgolden.me.uk> writes:

> My understanding is that PyLong_FromLongLong passes its reference
> to my function, which then passes it to PyDict_Set... which INCREFs
> it.

Your understanding is correct.

Note that the same reasoning doesn't apply to, for instance,
PyList_SetItem, which actually "steals" a reference to the value it
receives.  Fortunately, functions that behave in this fashion are very
rare, and clearly documented to do so.

> That means, I think, that my function should DECREF it before exit
> since I'm only creating it to store it in the dict. Is that correct?
>
> In other words, should my code really do this?
>
>   record_length = PyLong_FromLongLong (usn_record->RecordLength);
>   PyDict_SetItemString (dict, "RecordLength", record_length);
>   Py_DECREF (record_length)

Yes, and don't forget to check for PyLong_FromLongLong returning NULL:

if (!record_length) {
  Py_DECREF(dict);        /* presumably */
  return NULL;
}

(And of course the same goes for PyDict_SetItemString.)


More information about the capi-sig mailing list