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.