Why is sys.getrefcount giving huge values?

import sys

a = 10
b = a
print sys.getrefcount(a)
b=1
print sys.getrefcount(b)

      

output:

22 614

Is there a problem with my python interpreter? Why does this give huge values ​​like 614?

Python version

/usr/lib/python2.7/

+3


source to share


2 answers


This is due to the fact that internally CPython stores an already created integer object with a value of 1 and internal variables point to it. It makes sense to have only one such object since it is immutable.

The same goes for string literals, as they are immutable compilers, typically holding one unique string in memory and pointing to it in variables.

The more unique a literal is, the less likely it is to be created internally.



>>> sys.getrefcount(1337)
3
>>> sys.getrefcount('p')
14
>>> sys.getrefcount('StackOverflow')
3

      

As you can see in the internals, some small whole objects are created and cached for a little optimization. https://github.com/python/cpython/blob/2.7/Objects/intobject.c#L74

+4


source


You can see the effects of Python optimization (see @ Nether's answer) if you change the values ​​to non-trivial. For example, if your code is changed to:

from __future__ import print_function

import sys

a = 1012345
b = a
print(sys.getrefcount(a))
b=12345678
print(sys.getrefcount(b))

      



Output:

5
4

      

0


source







All Articles