Ref Count Checking

Bernhard Herzog bh at intevation.de
Thu Aug 30 07:28:08 EDT 2001


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

-- 
Intevation GmbH                                 http://intevation.de/
Sketch                                 http://sketch.sourceforge.net/
MapIt!                                               http://mapit.de/



More information about the Python-list mailing list