0

I tried to run sys.getrefcount for int(11) as below.

>>> a = 11
>>> b = 11
>>> id(a)
1845083728496
>>> id(b)
1845083728496
>>> id(11)
1845083728496
>>> import sys
>>> sys.getrefcount(a)
17
>>> sys.getrefcount(b)
17
>>> sys.getrefcount(11)
20

Why am i getting the result of 20 references to the number 11 and why it is higher than the reference count returned from a and b variables?.

But when i run the same as a standalone script, i am getting the same reference count for a, b and 11, as below.

import sys

a = 11
b = 11

print("a : {}".format(a))
print("b : {}".format(b))
print('-----------------')

print("hex of a: {}".format(hex(id(a))))
print("hex of a: {}".format(hex(id(b))))
print("hex of 11: {}".format(hex(id(11))))
print('-----------------')

print("ref count of a: {}".format(sys.getrefcount(a)))
print("ref count of b: {}".format(sys.getrefcount(b)))
print("ref count of 11: {}".format(sys.getrefcount(11)))

Output:

a : 11
b : 11
-----------------
hex of a: 0x2dfac546a70
hex of a: 0x2dfac546a70
hex of 11: 0x2dfac546a70
-----------------
ref count of a: 28
ref count of b: 28
ref count of 11: 28
mvk
  • 1
  • 1

1 Answers1

0

Your concern is right. So It can't happen because sys.getrefcount() function tells you the reference count of an object.

I tried to run sys.getrefcount for int(11) as below.

>>> a = 11
>>> b = 11
>>> id(a)
1845083728496
>>> id(b)
1845083728496
>>> id(11)
1845083728496
>>> import sys
>>> sys.getrefcount(a)
17
>>> sys.getrefcount(b)
17
>>> sys.getrefcount(11)
20

So according to this code, you should get one answer. So I try this code from my pyharm IDE but that time its working correctly.

a = 11
b = 11

print(id(a))
#2452752788080
print(id(b))
#2452752788080
print(id(11))
#2452752788080
import sys
print(sys.getrefcount(a))
#30
print(sys.getrefcount(b))
#30
print(sys.getrefcount(11))
#30

And your 2nd code also working correctly. I supposed you using jupitor notebook or something kind of ide to write your 1st code. So I supposed that ide's Interactive prompts can have a lot going on behind the scenes. So I supposed that is the reason you didn't get the correct answer.

  • I have used shell (windows cmd) to run 1st code. I have tried again and it gives the same result. – mvk Sep 15 '21 at 11:22
  • Try normal IDE like pycharm,vs coding then you can realize the difference. – Dilshan Madhuranga Sep 15 '21 at 11:25
  • I am using atom and it looks fine if i run in it. But if i run the same in the Python shell [v3.9.6] i am getting this difference. Can you please try running the same in the shell at your end. Thanks! – mvk Sep 15 '21 at 12:25
  • 1
    https://stackoverflow.com/a/22550758/16915611 refer this one you can solve your problem. – Dilshan Madhuranga Sep 15 '21 at 12:42