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

Dick Moores rdm at rcblue.com
Tue Oct 3 14:01:27 CEST 2006


At 04:44 AM 10/3/2006, Kent Johnson wrote:
>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

Ah, got it. Thanks again, Kent.

Dick




More information about the Tutor mailing list