Hello Daniel,

Thanks for the reply.


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?

 It really depends on /how/ the object is created. If the
method used to create *py_val* increases the reference count
on the object and another function any other function is
used to increase the reference count, you should use Py_DECREF
or Py_XDECREF.


So for example:

PyObject *py_val = PyInt_FromLong(5)
PyObject_SetAttrString(py_obj, "val", py_val);
Py_DECREF(py_val)

Right?

 In this case is right. *PyInt_FromLong()* returns a new
reference: 'Return value: New reference.', which is increasing
the reference count and PyObject_SetAttrString does it twice,
then you have a reference count of two and you need to decrement
the initial reference counting of the object, or you will have
a memory leak.


[quote]
int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v)
Set the value of the attribute named attr_name, for object o, to the value v. Returns -1 on failure. This is the equivalent of the Python statement o.attr_name = v.
int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v)
Set the value of the attribute named attr_name, for object o, to the value v. Returns -1 on failure. This is the equivalent of the Python statement o.attr_name = v.
[/quote]

Looking at the documentation, should I have understood that the passed value reference will be incremented and that I should decrement it if I don't need it?

Or I should have understood just because of the fact that whenever we have x = b (be it from the C api in a form of SetAttr()) then we should know that b's reference will be incremented. ?

Because, before this discussion I did not know I should decrease the reference after SetAttr()


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 think that Py_None do not needs to decrease the
reference count...


None is an object like other objects. I think its reference must be taken into consideration too, for instance why there is the convenience macro: Py_RETURN_NONE ?

--
Elias
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to