Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sys.getrefcount() prints one more than the expected number of references to an object?

I would like to know why this code prints 4 instead of 3. Where is the fourth reference?

import sys

def f(a):
    print(sys.getrefcount(a))

a = [1, 2, 3]
f(a)
like image 836
ThunderPhoenix Avatar asked Nov 16 '19 23:11

ThunderPhoenix


1 Answers

We can make sense of this in steps:

import sys

print(sys.getrefcount([1, 2, 3]))
# output: 1
import sys

a = [1, 2, 3]
print(sys.getrefcount(a))
# output: 2
import sys

def f(a):
    print(sys.getrefcount(a))

f([1, 2, 3])
# output: 3
import sys

def f(a):
    print(sys.getrefcount(a))

a = [1, 2, 3]
f(a)
# output: 4

So to reiterate:

  • First reference is the global variable a
  • Second reference is the argument passed to the f function
  • Third reference is the parameter that the f takes
  • Fourth reference is the argument passed to the getrefcount function

The reason for no fifth reference, from the parameter getrefcount takes, is that it's implemented in C, and those don't increase the reference count in the same way. The first example proves this, since the count is only 1 in that.

like image 146
ruohola Avatar answered Nov 01 '22 16:11

ruohola