I was going through the tutorial for defining 'new types' in python, https://docs.python.org/2/extending/newtypes.html, and I did not understand the purpose of using Py_DECREF in this piece of code.
static PyObject *
Noddy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
Noddy *self;
self = (Noddy *)type->tp_alloc(type, 0);
if (self != NULL) {
self->first = PyString_FromString("");
if (self->first == NULL)
{
Py_DECREF(self);
return NULL;
}
self->last = PyString_FromString("");
if (self->last == NULL)
{
Py_DECREF(self);
return NULL;
}
self->number = 0;
}
return (PyObject *)self;
}
My understanding of reference counting is patchy and any help would be appreciated.
The CPython Garbage Collector uses 'Reference Counting', i.e it maintains a list of references to an object. If the reference count of an object falls to zero, it then implies that it is safe for the garbage collector to deallocate space for that object.
Hence, when we define PyObjects it is imperative that we explicitly call Py_INCREF and Py_DECREF, which increase and decrease reference counts of an object respectively.