Ref Count Checking

Robin Becker robin at jessikat.fsnet.co.uk
Sat Aug 25 16:00:45 EDT 2001


In article <mailman.998764178.19787.python-list at python.org>, Ignacio Vazquez-Abrams
<ignacio at openservices.net> writes
>On Sat, 25 Aug 2001, Robin Becker wrote:
>
>> As part of an extension debugging exercise I printed refcounts
>> relating to the structure
>> ('a1', {'z1': 'az1'}, ['b1', ('c1', {'y1': 'ay1'}, ['d1'], None), 'e1'], None)
>> either created directly in Python or by my extension.
>>
>>
>> An earlier pass revealed values of decrementing values
>> for the None output from the extension (it was stealing a None).
>> After Correcting I'm still getting differences.
>> In particular the strings az1, ay1, b1, c1, d1, e1 seem to have counts from 
>the
>> extension which are 3 lower than from the python version.
>>
>> Is there any way to deduce what the python count should be?
>> I'm assuming that a string like az1 is reasonably unique so there
>> shouldn't be any question of a library reference.
>
>Your extension is probably still using a borrowed reference and not
>incrementing its refcount. Have a look at
>http://www.python.org/doc/current/api/api.html and note which functions return
>borrowed references and which return new references.
well for the dictionary {'z1':'az1'} I use

PyDict_SetItemString(attrs, (char*)a->definition->name, t=PyString_FromString(a->value));
Py_DECREF(t);

I assume that the insertion adds 1 to the ref count and
the temporary ref t is not needed any more. There's no mention of
stealing/borrowing in the docs for PyDict_SetItemString.

Anyway that still doesn't answer my question. How to deduce the ref count
in a python struct.

>>> p=('a1', {'z1': 'az1'}, ['b1', ('c1', {'y1': 'ay1'}, ['d1'], None), 'e1'], None)
>>> from sys import getrefcount as rc
>>> rc(p[1]['z1'])
4

the value 4 seems a little high to me. I see only one 'az1' and I can imagine that p[1]['z']
grabs another reference to it. I make the proper count 2 ie one ref in the Dict and one for the
argument to rc. Where do the other 2 come from?

Are the strings being interned or something? Why do the following simpler cases
differ?

>>> p={'z1': 'az1'}
>>> rc(p['z1'])
4
>>> p={'z1': 9999999}
>>> rc(p['z1'])
2
>>> 
-- 
Robin Becker



More information about the Python-list mailing list