[Python-ideas] simpler weakref.finalize

Matthew Stoltenberg d3matt at gmail.com
Mon Apr 11 17:22:25 EDT 2016


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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160411/6dcfaa39/attachment.html>


More information about the Python-ideas mailing list