3

As explained in this other answer, sys.getrefcount() returns a value 1 higher than expected because when invoking the function for an object, a new reference to that object has to be created. For example, the following would print 2, instead of of 1:

import sys
class Foo:
    pass

foo = Foo()
print(sys.getrefcount(foo))  # returns 2

I am making a python c extension and want to add some regression tests to make sure the reference counting is incrementing and decrementing as expected.

Is it safe to have a test that always returns sys.getrefcount(...) - 1 ?

class TestFoo(unittest.TestCase):
    def assert_reference_count(self, obj, expected_reference_count):
        self.assertEquals(sys.getrefcount(obj) - 1, expected_reference_count)

I figure there must be a reason why sys.getrefcount doesn't do this automatically. Perhaps there are some instances where it would not increment by 1, for example.

Matthew Moisen
  • 16,701
  • 27
  • 128
  • 231
  • 1
    The documentation says *"The count returned is **generally** one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount()."* (emphasis mine), which does suggest it might sometimes *not* be "one higher than you might expect", but I cannot imagine any such situation. My best guess is that subtracting 1 is always correct, but not sure how to prove it. – kaya3 Jan 13 '20 at 18:41

0 Answers0