weakref.finalize works too well?
I've been trying to learn more about weakref.finalize, which I've seen as a cleanup alternative to del that's more flexible than using enter and exit. I can make it work, but it seems like it works past what is guaranteed, so I want to step back and make sure I understand it better. The documents state very clearly that the finalizer function shouldn't be a bound method of the finalized object, because that would count as a reference.
It is important to ensure that func, args and kwargs do not own any references to obj, either directly or indirectly, since otherwise obj will never be garbage collected. In particular, func should not be a bound method of obj.
However, the following code does just that, yet the finalizer still runs just fine. Why is that? What circumstances could cause code like this to fail, if running it normally like this is successful?
#!/usr/bin/env python3
import weakref
class TestClass:
def __init__(self):
print("Enter __init__")
print("Proof that the method is bound:", self.my_method)
self.finalizer = weakref.finalize(self, self.my_method)
def my_method(self):
print("Cleaning:", str(self.__dict__))
if __name__ == '__main__':
TestClass()
~~~
Enter __init__
Proof that the method is bound: <bound method TestClass.my_method of <__main__.TestClass object at 0x7fd2e5098090>>
Cleaning: {'finalizer': <finalize object at 0x7fd2e511b8e0; dead>}
Thanks!