4

Out of curiosity, I am trying to understand how reference counting works in Python. These two entries:

were helpful, but still raised questions.

  1. Using sys.getrefcount() returns a different value than len(gc.get_referrers()). For example:

    >>> a = 3
    >>> print sys.getrefcount(a)
    38
    >>> print len(gc.get_referrers(a))
    23
    

    Why the difference?

  2. As I understand it, the reference count on a is so high because there is already an object holding an integer value of 3 at the time I bound the name a to it. How does Python keep track of which object is holding 3 so that it binds the name a to it and increments its reference count accordingly?

Community
  • 1
  • 1

1 Answers1

0
  1. gc.get_referrers only returns objects the cycle-detecting GC knows about. Objects that couldn't possibly be involved in a reference cycle don't need to be tracked by the cycle detector, so they might not show up in the get_referrers list.
  2. With this array here:

    static PyIntObject *small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
    
user2357112
  • 260,549
  • 28
  • 431
  • 505