python extension: incref question

David Rushby woodsplitter at rocketmail.com
Mon Feb 23 06:42:17 CET 2004


John Hunter <jdhunter at ace.bsd.uchicago.edu> wrote in message news:<mailman.171.1077471512.27104.python-list at python.org>...
> I am writing a python extension and have a question about reference
> counting on an attribute I set.
> ... 
> I infer from this that since a new ref is created by PyInt_FromLong,
> and PyDict_SetItemString doesn't take ownership, that I should
> decrease the reference count in my types dealloc function.  Is this
> correct?

Mostly.  You're right about the reference ownership (PyDict_SetItem
creates its own reference (see Python 2.3.3
Objects/dictobject.c:531)).  However, I would recommend disposing of
the extra reference not in your type's dealloc function, but as soon
as you've sent the value to Glyph_setattr.  Something along the lines
of:
---
PyObject *val = PyInt_FromLong(self->face->glyph->metrics.width);
if (val == NULL) {
  return PyErr_NoMemory();
}
int gsetResult = Glyph_setattr(gm, "width", val);
Py_DECREF(val);
if (gsetResult == -1) {
  ...
}
---
That way, you will have disposed of the extra reference to val as soon
as it's no longer needed.  In your type's dealloc function, you can
simply Py_XDECREF(self->x_attr), and x_attr will dispose of its own
reference to val.

If you were to wait to dispose of the extra reference until your
type's dealloc function were called, but in the meantime
Glyph_setattr(gm, "width", ...) were called again, the extra reference
to val would be lost in the shuffle.



More information about the Python-list mailing list