Reference counts

Isaac To Kar Keung kkto at csis.hku.hk
Thu May 24 04:13:15 EDT 2001


>>>>> "Helen" == Helen Dawson <helend at accessone.com> writes:

    Helen> I understand that the objects for numbers from 0 to 100 are
    Helen> shared, but I find it unlikely that there are actually 1495
    Helen> references to zero, and 70 to 15. Zero is a popular number, but
    Helen> 1495? These results are typical for absolutely nothing happening
    Helen> in Python

Not too surprising to me, although in Python 1.5.2 the initial numbers are
just 95 and 5.

    Helen> However, the problem with that is that getrefcount() for any
    Helen> negative integer returns 1!

    >>>> sys.getrefcount(-2)
    Helen> 1

    Helen> Any thoughts?

Not too surprising.  It is an expression, and the result of the expression
will be deleted after the call, so it is quite possible that when the method
is called, the reference count held by the caller is stolen by (or given to)
the callee.  Example:

  sys.getrefcount(0)      => 95
  sys.getrefcount(100+15) => 1
  sys.getrefcount(0+0)    => 95

What surprised me is that negative numbers are not shared.  Or more
precisely, only -1 is shared:

  sys.getrefcount(-1)     => 2
  a = -1
  sys.getrefcount(-1)     => 3

Regards,
Isaac.



More information about the Python-list mailing list