0

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?

1
  • 1
    From the "getrefcount" call itself which has to hold a reference to work. This is exactly what the docs tell you. Commented Jul 12, 2022 at 6:37

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

According to VSCode PyLance, the signature is like def getrefcount(__object: Any) -> int: .... So the extra count is held by the __object?
@qrsngky I'm not familiar with PyLance, but it seems so.
1

See Python Docs: https://docs.python.org/3/library/sys.html#sys.getrefcount It referred to that:

sys.getrefcount(object)

Return the reference count of the object. The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.