[Python-3000] Removing __del__

Raymond Hettinger rhettinger at ewtllc.com
Sat Sep 23 01:24:48 CEST 2006


Giovanni Bajo wrote:

>I don't use __del__ much. I use it only in leaf classes, where it surely can't
>be part of loops. In those rare cases, it's very useful to me. For instance, I
>have a small classes which wraps an existing handle-based C API exported to
>Python. Something along the lines of:
>
>class Wrapper:
>    def __init__(self, *args):
>           self.handle = CAPI.init(*args)
>
>    def __del__(self, *args):
>            CAPI.close(self.handle)
>
>    def foo(self):
>            CAPI.foo(self.handle)
>
>The real class isn't much longer than this (really). How do you propose to
>write this same code without __del__?
>  
>
Use weakref and apply the usual idioms for the callbacks:

class Wrapper:
    def __init__(self, *args):
           self.handle = CAPI.init(*args)
	   self._wr = weakref.ref(self, lambda wr, h=self.handle: CAPI.close(h))

    def foo(self):
            CAPI.foo(self.handle)



Raymond



More information about the Python-3000 mailing list