python - What is the purpose of Py_DECREF and PY_INCREF? -
i going through tutorial defining 'new types' in python, https://docs.python.org/2/extending/newtypes.html, , did not understand purpose of using py_decref in 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 patchy , appreciated.
in case, py_decref free memory allocated tp->alloc.
tp->alloc sets ref count 1. py_decref decreases ref count 1 0; finds ref count 0, calls appropriate functions free memory (noddy_dealloc in case.)
if python c api function returns null, has gone wrong; exception set (saved in global variable).
if caller returns null again, exception chained, hence 'return null'.
Comments
Post a Comment