Currently, if I want to have weakref.finalize call an object's cleanup method, I have to do something like:
class foo:
_finalizer = None
def __init__(self):
self._finalizer = weakref.finalize(self,
foo._cleanup,
weakref.WeakMethod(self.cleanup))
def __del__(self):
self.cleanup()
@classmethod
def _cleanup(cls, func):
func()()
def cleanup(self):
if self._finalizer is not None:
self._finalizer.detach()
print('cleaning up')
It wouldn't be difficult to have weakref.finalize automatically handle the conversion to WeakMethod and automatically attempt to dereference then call the function passed in.