How to modify object attribute by python C API

Ben Sizer kylotan at gmail.com
Fri Jan 12 05:05:13 EST 2007


Huayang Xia wrote:

>     PyObject* py_obj_attr1 = PyObject_GetAttrString(obj, "attr1");
>     PyObject_SetAttrString(py_obj_attr1, "attr2",
> PyString_FromString("a"));
>     Py_DECREF(py_obj_attr1);
>
> The object py_obj_attr1 is said to be a "New reference". It's
> confusing, does it refer to the same object as "obj.attr1" in python's
> term?

Yes, it refers to the same object. Each object can have many
references, and is deleted when all the references are gone. The new
reference in this case means that Python has taken note that there's a
new use of that object - your C code. It means it won't delete that
object, even if no more Python code refers to it, because it knows your
C code holds a reference to it. Therefore, when your C code no longer
needs to access the object, you call Py_DECREF.

-- 
Ben Sizer




More information about the Python-list mailing list