I want to a method that runs when object reference count is changed. is there a method like the following code ?
class Foo():
def __method__(self):
print("ojbect reference count is changed !")
a = Foo()
b = a # runs __method__ because the reference count is increased
c = b # runs __method__ because the reference count is increased
del b # runs __method__ because the reference count is decreased
del c # runs __method__ because the reference count is decreased
Note: This is a repost of this question, I'm looking for an answer compatible with Python 3.10.
Thanks!
The reference count of my object never goes below 1. Taking this as a given, I tried to implement some clean-up code for when an object is dereferenced by all user-facing code by adding __del__. That didn't work, because there's one reference left.
So, I need to add some clean-up code for the reference count hits 1.
This is an XY Problem, and I'm comfortable with that. My actual situation involves singletons, wherein ((User("my_name") == User("my_name")) and (User("my_name") != User("other_name"))) is True. To do this, there's an internally referenced dictionary that's handling all this. That's why the minimum reference count for an object is 1.
When an object is removed from the User's code, ie, the reference count reaches 1, I'd like to clean it up from my reference dictionary as well.
I'm afraid there's no magic method like that in Python. However, if you're looking to implement a singleton with auto-cleanup, using a
WeakValueDictionarywould work:You can test this works as expected like so:
See: