Question about PyDict_SetItemString

Hrvoje Niksic hniksic at xemacs.org
Fri Jul 13 05:32:15 EDT 2007


lgx <lgxror at gmail.com> writes:

>From Google results, I find some source code write like that. But
>some code write like below:
>
> obj =  PyString_FromString("value");
> PyDict_SetItemString(pDict,"key",obj);
> Py_DECREF(obj);
>
> So, which one is correct?

The latter is correct.  While PyDict_GetItemString returns a borrowed
reference, PyDict_SetItemString doesn't steal the reference.  This
makes sense because adding to the dictionary can fail for various
reasons (insufficient memory, invalid key, hash or comparison
functions failing), and that allows you to write code like this:

obj = <something that creates the object>;
int err = PyDict_SetItemString(dict, "key", obj);
Py_DECREF(obj);
if (err)
  return NULL;   /* or whatever is appropriate in your case */

That won't leak regardless of whether PyDict_SetItemString succeeded,
and will correctly propagate an error if it occurs.

Please note that there is a new mailing list for Python/C API
questions, see http://mail.python.org/mailman/listinfo/capi-sig .



More information about the Python-list mailing list