1

I'm maintaining a Python type that has been built as a Python extension using the Python C API. My question is regarding the lifetime of this "NamedArray" object. Essentially my test code looks like this:

    def test_init_from_constructor(self):
        """

        :return:
        """
        n = NamedArray((2, 3))
        self.assertIsInstance(n, NamedArray)
        self.assertEqual(2, sys.getrefcount(n))

My issue is that the ref count of the newly instantiated NamedArray object is 2, yet I expect it to be 1. Where is the other reference coming from ?

CiaranWelsh
  • 7,014
  • 10
  • 53
  • 106

1 Answers1

5

This is documented under sys.getrefcount

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

Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46
  • 1
    Abdul already answered the question, but this online article might be relevant as well. For primitive types, such as integers, some might even have over 500 references by default! Strings have a high number of default references as well. https://groverlab.org/hnbfpr/2017-06-22-fun-with-sys-getrefcount.html – waykiki Sep 29 '21 at 12:25