ivan
ivan

Reputation: 1

PYthon 3.6.- mystical sys.getrefcount() (simple example- strange result)

I have such code

import sys
test = 1
vvv = test
vvv = 5
print(sys.getrefcount(test))
print(sys.getrefcount(vvv))

I expect 2 and 1 оr 1 and 1? but i get such result

836 37

Why do i have such result?

Or simplier

import sys
test = 1
vvv = test
print(sys.getrefcount(test))
print(sys.getrefcount(vvv))

And the result is 837 837

Upvotes: 0

Views: 58

Answers (1)

gilch
gilch

Reputation: 11681

Small integers are interned in CPython. So numbers like 1 and 5 are used in many places in the standard library. The literal 1 refers to the same object, no matter how many times you use it, rather than creating a new one each time, which would be inefficient. Last I checked, this applies to the range [-5, 256], but this is an implementation detail that you should not rely on.

If you want to see a small refcount, try making a new object instead of re-using an existing one, like

>>> test = object()
>>> sys.getrefcount(test)
2

Obviously the refcount here can't be 1, because you passed it as an argument to a function (getrefcount itself), which creates a local variable inside that function.

But if you didn't assign it first,

>>> sys.getrefcount(object())
1

what about print(sys.getrefcount('j989898989jj')) - it returns 3

CPython also interns most string literals that are valid Python identifiers, which speeds up attribute access. The exact rules are an implementation detail that you should not rely on. Generating a string fresh yields the expected ref count of 1.

>>> sys.getrefcount(str(98989898j))

1

Upvotes: 2

Related Questions