Refrence Counting

Lyle Johnson ljohnson at resgen.com
Tue Jun 19 15:24:36 EDT 2001


>  Do I need to decrement the
> reference count for the second dictionary below (grades)?  When I use
> PyStringFromString() it creates the object with a reference count of
> one, then it is added to my dictionary with PyDict_SetItem() does this
> increment it again?  Should I create it in a seperate step then use
> PyDict_SetItem() and then decrement it?

A call to PyDict_SetItem(dict, key, value) increments the reference count
for both the "key" and the "value", so yes, you should decrement the
reference count for the "grades" object. Similarly, when you create the new
string keys using PyString_FromString() I think you're probably ending up
with one-too-many references for each of those, but I'm not sure how Python
2.0's new garbage collector plays into this.

The online Python/C API documentation is very good about letting you know
which functions return new references versus borrowed references and so on,
but when in doubt I usually end up going straight to the source. In this
case, the file of interest is Objects/dictobject.c. As others will tell you,
the source code is extremely readable even if you're not familiar with
Python's internals.

Hope this helps,

Lyle






More information about the Python-list mailing list