Discussion:
Does PyObject_SetAttrString am PyArg_Parse steal an object reference?
Robert Steckroth
2012-12-05 19:14:43 UTC
Permalink
In the below example, is there an extra reference to the align object when
the Py_RETURN_NONE IS hit? Also, why do I have to Py_INCREF(s_obj)? If I do
not, I end up with crashes. Is this a bug?

PyObject *s_obj=NULL, *align=NULL;
if ( ! PyArg_ParseTupleAndKeywords(args, kwds, "|OO", kwlist, &s_obj,
&align) )
return NULL;

if ( s_obj ) Py_XINCREF(s_obj);

if ( align ) { Py_XINCREF(align);
PyObject_SetAttrString(s_obj, "align", align); }

Py_RETURN_NONE; }
--
Bust0ut, Surgemcgee: Systems Engineer ---
surgemcgee.com
Django_Teamplate3d
Hrvoje Niksic
2012-12-06 07:42:20 UTC
Permalink
Post by Robert Steckroth
In the below example, is there an extra reference to the align object
when the Py_RETURN_NONE IS hit?
There is. Since PyObject_SetAttrString doesn't steal the reference
count to its argument, the Py_XINCREF is unnecessary. Also, I'd use
Py_INCREF there, since you already aren't entering the if-clause if
align is NULL.
Post by Robert Steckroth
Also, why do I have to Py_INCREF(s_obj)?
You don't. PyArg_ParseTupleAndKeywords doesn't increase reference count
of its arguments, and neither should the code calling it -- it is the
responsibility of the caller to provide arguments that it either owns or
are globally available (Py_None, type objects).
Post by Robert Steckroth
If I do not, I end up with crashes. Is this a bug?
It's most likely a bug somewhere else in your code or an extension
you're using that gets hidden by the extra incref. This can sometimes
happen in Python/C; the correct solution is to remove the extraneous
incref and carefully inspect the rest of your code for incorrect
reference count handling.

Loading...