Python C API and references
Mark Dickinson
dickinsm at gmail.com
Thu Nov 12 06:02:12 EST 2009
On Nov 12, 9:23 am, "lallous" <lall... at lgwm.org> wrote:
> Hello,
>
> Everytime I use PyObject_SetAttrString(obj, attr_name, py_val) and I don't
> need the reference to py_val I should decrement the reference after this
> call?
Not necessarily: it depends where py_val came from. I find the
'ownership' model described in the docs quite helpful:
http://docs.python.org/c-api/intro.html#reference-count-details
It's probably better to read the docs, but here's a short version:
If you create a reference to some Python object in a function in your
code, you then 'own' that reference, and you're responsible for
getting rid of it by the time the function exits. There are various
ways this can happen: you can return the reference, thereby
transferring ownership to the calling function; you can explicitly
discard the reference by calling Py_DECREF; or you can transfer
ownership by calling a function that 'steals' the reference (most
functions in the C-API don't steal references, but rather borrow them
for the duration of the function call).
>
> So for example:
>
> PyObject *py_val = PyInt_FromLong(5)
> PyObject_SetAttrString(py_obj, "val", py_val);
> Py_DECREF(py_val)
>
> Right?
Yes. Here you've created the reference in the first place, so you
should Py_DECREF it before you exit. Right after the
PyObject_SetAttrString call is a good place to do this.
>
> If so, take sysmodule.c:
>
> if (PyObject_SetAttrString(builtins, "_", Py_None) != 0)
> return NULL;
>
> Shouldn't they also call Py_DECREF(Py_None) ?
No, I don't think so. I assume you're looking at the sys_displayhook
function? This function doesn't create new references to Py_None
(well, except when it's about to return Py_None to the caller), so at
this point it doesn't own any reference to Py_None: it's not
responsible for decrementing the reference count.
> Same logic applies to PyDict_SetItemString()
Yes.
--
Mark
More information about the Python-list
mailing list