Reference counting

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri Aug 30 10:23:58 CEST 2002


Rolf Wester <wester at ilt.fhg.de> wrote in
news:3D6F1CC4.72EE5262 at ilt.fhg.de: 
> Terry Reedy wrote:
>> from python:
>> >>> import sys
>> >>> a = 3
>> >>> sys.getrefcount(a)
>> 10
> Thank you for your reply.
> Can you tell me why getrefcount(a) returns 10? I would have expected
> to get 1. 
> 
Small integers are shared in Python, so your 3 is the same 3 as is used 
elsewhere in the system. On my system:
>>> import sys
>>> a = 3
>>> sys.getrefcount(a)
28
>>> a = 345235
>>> sys.getrefcount(a)
2
>>> 

Note that even the larger value has a reference count of 2: 'a' refers to 
34235, and the parameter of getrefcount also refers to it.

You can use the 'id' builtin to see when values are being shared:

>>> a = 3
>>> b = 66/22
>>> id(a), id(b)
(7626576, 7626576)
>>> a = 300
>>> b = 6600/22
>>> id(a), id(b)
(7781700, 7781976)
>>> a = 'hello'
>>> b = 'hello'
>>> id(a), id(b)
(8210480, 8210480)
>>> 

The small integers are shared, the large integers are not. Some strings are 
also shared. The rules for when you end up with two references to the same 
object, and when you end up with references to separate object can be 
confusing, so it is best not to rely on them too much.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list