Why does
sys.getrefcount()
return 3 for every large number or simple string?Does that mean that 3 objects reside somewhere in the Program?Also,why doesn’t setting x=(very large number) increase that object’s ref count?Do those 3 ref counts result from my call to getrefcount?
Thank you for clarifying this.
for instance:
>>> sys.getrefcount(4234234555)
3
>>> sys.getrefcount("testing")
3
>>> sys.getrefcount(11111111111111111)
3
>>> x=11111111111111111
>>> sys.getrefcount(11111111111111111)
3
Large integer objects are not reused by the interpretor, so you get two distinct objects:
sys.getrefcount(11111)always returns the same number because it measures the reference count of a fresh object.For small integers, Python always reuses the same object:
Usually you would get only one reference to a new object:
But integers are allocated in a special pre-malloced area by Python for performance optimization, and I suspect the extra two references have something to do with this.
It’s implemented in longobject.c in CPython. (Update: link to Python3.) I do not claim to understand what’s really going on. I think there are several things at work that cache temporary references: