[Tutor] Is there Python code for accessing an object's reference count?

Kent Johnson kent37 at tds.net
Tue Oct 3 13:44:35 CEST 2006


Dick Moores wrote:
> At 03:25 AM 10/3/2006, Andre Roberge wrote:
>> On 10/3/06, Dick Moores <rdm at rcblue.com> wrote:
>>> Is there Python code for accessing an object's reference count?
>> See sys.getrefcount.
> 
> Fascinating. And surprising.
>  >>> from sys import getrefcount
>  >>> getrefcount(1)
> 493
>  >>> getrefcount(2)
> 157
>  >>> getrefcount(3)
> 60
>  >>> getrefcount(22)
> 12
>  >>> getrefcount(222)
> 3
>  >>> getrefcount(222234523452345345)
> 2
>  >>> getrefcount(2.23452345345)
> 2
>  >>>
> 
> That refcount for 1 (and 2, 3, and 12) is puzzling to me. I closed 
> python, called python,  and tried it again. Essentially no change. 
> When would this go to zero? Only when I shut off my computer?

When you exit Python.

There are quite a few modules loaded automatically when Python starts 
up. It's not too surprising that a few of them reference 1. For example, 
defining a function that uses a constant creates a reference to the 
constant:
In [2]: sys.getrefcount(100)
Out[2]: 43

In [3]: def foo():
    ...:     return 100
    ...:

In [4]: sys.getrefcount(100)
Out[4]: 44

Kent



More information about the Tutor mailing list