Ref Count Checking

Robin Becker robin at jessikat.fsnet.co.uk
Thu Aug 30 09:10:37 EDT 2001


In article <6qofoxbxdj.fsf at abnoba.intevation.de>, Bernhard Herzog
<bh at intevation.de> writes
>Robin Becker <robin at jessikat.fsnet.co.uk> writes:
>
>> well I don't have to do that in my extension and things seem to work fine with 
>the external
>> results. Perhaps I'm being naive when I do
>> 
>> PyDict_SetItemString(attrs, name, t=PyString_FromString(sValue));
>> Py_DECREF(t);
>> 
>> ie I haven't interned anything.
>
>PyDict_SetItemString interns the keys.
>
>In the following example the interpreter interned a few strings for you:
>
>> Would the module need two extra refs as in
>> 
>> >>> from sys import getrefcount as rc
>> >>> p={'az1': 99999}
>
>99999 is not in the range of shared ints (range(-1, 100) by default
>IIRC), so after this statement there's exactly one reference to it in p.
>(During execution there were more references because literals are stored
>in code objects and they get put on the stack etc., but the code object
>and stack have been collected at this point)
>
>> >>> q={'az2': 'az3'}
>
>Here it's a little different because 'az3' is a string that looks like
>an identifier. These strings are always interned, so there are now 3
>references, one from the dict q, and 2 from interning. Interning takes 2
>refs because there's a dict of all interned strings which has the
>interned strings as both keys and values.
>
>> >>> rc(p['az1']), rc(q['az2'])
>
>When you pass an object to getrefcount it's put into the argument tuple
>python builds for every function call, so the value returned by
>getrefcount is always at least one higher than one might expect.
>
>> (2, 4)
>
>Thus, this is exactly what you should get for the dfault configuration
>of the CPython interpreter.
>
>   Bernhard
>

Yes OK I thought the interning must be the difference. When I get this
out of my extension I haven't interned the value so I see only a 2 count
for q['az2'] ie one for the dict and 1 for the rc(arg).

At least that lets me rest a bit easier about what my extension is
doing.
-- 
Robin Becker



More information about the Python-list mailing list