I’m a little confused with the reference counts I see from my test code
JavaScript
x
17
17
1
1 import sys
2
2
3
3 class Square():
4
4 def __init__(self, width, color):
5
5 self.width = width
6
6 self.color = color
7
7
8
8 oSquare1 = Square(5, 'red')
9
9 print(oSquare1)
10
10 # Reference count of the Square object should be 1
11
11 print ('Reference Count is ', sys.getrefcount(oSquare1))
12
12
13
13 oSquare2 = oSquare1
14
14 print(oSquare2)
15
15 # Reference count of the Square object should be 2
16
16 print ('Reference Count is ', sys.getrefcount(oSquare1))
17
When I run my code in both python2 and python3, it shows the reference count is off by 1. Where did the extra reference count come from?
JavaScript
1
8
1
$ python3 p.py
2
<__main__.Square object at 0x7fea7f72ebe0>
3
# reference should be 1 but the print statement says 2
4
Reference Count is 2
5
<__main__.Square object at 0x7fea7f72ebe0>
6
# reference should be 2 but the print statement says 3
7
Reference Count is 3
8
So what happened? Why is it off by 1? Where did the extra count come from?
Advertisement
Answer
Did you look at the source code or the docs for getrefcount()
JavaScript
1
10
10
1
def getrefcount(): # real signature unknown; restored from __doc__
2
"""
3
Return the reference count of object.
4
5
The count returned is generally one higher than you might expect,
6
because it includes the (temporary) reference as an argument to
7
getrefcount().
8
"""
9
pass
10