When to use Py_INCREF(x) and Py_DECREF(x)

William Park parkw at better.net
Wed Oct 25 12:14:01 EDT 2000


On Wed, Oct 25, 2000 at 02:38:24PM +0000, Opinderjit wrote:
> I am confused with when to use Py_INCREF(x) and Py_DECREF(x). In the
> following example, I am creating a dictionary object, populating it,
> and returning it back to Python. Should I use Py_INCREF(dict) to
> increase the dictionary object's reference count?
> 
> Thanks.
> 
> PyObject *dict;      // Metadata dictionary
> dict = PyDict_New();
> while (pos != NULL)
> {
>    ...
>    // Name is a string
>    // Value is a string
>    PyDict_SetItemString(dict, Name, PyString_FromString(Value));
>    delete Name;
> }
> return dict;

No.  'PyDict_New()' makes a new object and returns the first reference
to that object.  Same with 'PyString_FromString()'.

---William Park, Open Geometry Consulting




More information about the Python-list mailing list