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)) 23
Why the difference?
As I understand it, the reference count on
a
is so high because there is already an object holding an integer value of3
at the time I bound the namea
to it. How does Python keep track of which object is holding3
so that it binds the namea
to it and increments its reference count accordingly?