Out of curiosity, I am trying to understand how reference counting works in Python. These two entries:
- Why are Python Ref Counts to small integers surprisingly high?
- Is there a way to get the current ref count of an object in Python?
were helpful, but still raised questions.
Using
sys.getrefcount()returns a different value thanlen(gc.get_referrers()). For example:>>> a = 3 >>> print sys.getrefcount(a) 38 >>> print len(gc.get_referrers(a)) 23Why the difference?
As I understand it, the reference count on
ais so high because there is already an object holding an integer value of3at the time I bound the nameato it. How does Python keep track of which object is holding3so that it binds the nameato it and increments its reference count accordingly?