2

After reading about sys.getrefcount, I tried to play with it with the code below:

import sys
go = 102133333333333333333333333
sys.getrefcount(go)
>>> 2
sys.getrefcount(102133333333333333333333333)
>>> 3

Why am I getting this result, in particular the result of 3 references to the 102133333333333333333333333 number (or any high number, for that matter), and why it's higher than the reference count returned from the go variable?

Maroun
  • 94,125
  • 30
  • 188
  • 241
Yuval Pruss
  • 8,716
  • 15
  • 42
  • 67
  • 1
    The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount(). – Vishnu Upadhyay Jul 10 '17 at 13:46

1 Answers1

3

The getrefcount function returns the number of references, including:

  1. The reference created for the argument;
  2. All the references defined in the imported code.

Therefore, 1 which is pretty common, and most likely used a lot in the built-in modules, gives a lot of references:

>>> getrefcount(1)
136

The same applies for other immutable objects, such as strings and constants:

>>> getrefcount(True)
145
>>> getrefcount("a")
5

On my system, 102133333333333333333333333 gives 3 as well, which means that it is used twice in the code that was imported at the opening of the interpreter.


So why do you get these results?

Regarding the go variable, it has two references: one created when you define it, and another one when you pass it to getrefcount.

Now about 102133333333333333333333333, or any large number. First off, this question explains why large numbers lead to 3 references. Basically, small numbers are used in compiled code, and all the places where they are used point towards the same address. On the other hand, when creating a number at runtime that doesn't exist in the compiled code, it is compiled and stored for optimization, which gives two references, plus the one passed to getrefcount.

But when a runtime number is assigned to two variables, the latter will not point towards the same address. Therefore, the number of references will not increase, and stay at 3.

Here is the demonstration:

>>> getrefcount(45)
9
>>> a = 45
>>> b = 45
>>> a is b
True

Now with a larger number:

>>> getrefcount(1000)
3
>>> a = 1000
>>> b = 1000
>>> a is b
False

The following shows how variables will not point towards the number address:

>>> a = 1000
>>> a is 1000
False
Right leg
  • 16,080
  • 7
  • 48
  • 81