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

Tim Golden mail at timgolden.me.uk
Fri Jul 2 12:16:19 CEST 2010


On 02/07/2010 11:02, Hrvoje Niksic wrote:
> 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.)

Thanks for that, Hrvoje

TJG


More information about the capi-sig mailing list