I have a pretty basic doubt in Python. Is there a function that is called when the ref count of an object is being increased?
I am sure there should be a double underscore method that I can override in my class. Basically I am looking for a ref method in Foo class.
class Foo():
def __ref__(self):
print ("refcount increased by 1")
ref1 = Foo()
ref2 = ref1 # prints "refcount increased by 1"
ref3 = ref2 # prints "refcount increased by 1"
PS: I am aware of sys.getrefcount
There's no such hook. It'd break all kinds of stuff, including C-level code that relies on the ability to incref objects without triggering interpreted code. It'd be incompatible with non-refcounted Python implementations (which is most of them). It'd be incompatible with any hypothetical future non-refcounted CPython implementations (unlikely as such would be). It'd be incompatible with itself, because the mere act of calling or leaving such a method would alter the object's refcount, requiring it to trigger again infinitely, and doing anything with the object inside the method would also modify the refcount and cause another trigger even if you could reach the method body.