Skip to content
Advertisement

Confused with reference count of objects in Python

I’m a little confused with the reference counts I see from my test code

  1 import sys
  2 
  3 class Square():
  4     def __init__(self, width, color):
  5         self.width = width
  6         self.color = color
  7         
  8 oSquare1 = Square(5, 'red')
  9 print(oSquare1)
 10 # Reference count of the Square object should be 1
 11 print ('Reference Count is ', sys.getrefcount(oSquare1))
 12 
 13 oSquare2 = oSquare1
 14 print(oSquare2)
 15 # Reference count of the Square object should be 2
 16 print ('Reference Count is ', sys.getrefcount(oSquare1))

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?

$ python3 p.py
<__main__.Square object at 0x7fea7f72ebe0>
# reference should be 1 but the print statement says 2
Reference Count is  2
<__main__.Square object at 0x7fea7f72ebe0> 
# reference should be 2 but the print statement says 3
Reference Count is  3

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()

def getrefcount(): # real signature unknown; restored from __doc__
    """
    Return the reference count of object.
    
    The count returned is generally one higher than you might expect,
    because it includes the (temporary) reference as an argument to
    getrefcount().
    """
    pass
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement