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