[Python-3000] Removing __del__

Giovanni Bajo rasky at develer.com
Wed Sep 20 15:36:48 CEST 2006

Jean-Paul Calderone wrote:

>>> Since we're apparently still in "propose wild ideas" mode for Py3K
>>> I'd like to propose that for Py3K we remove __del__. Not "fix" it,
>>> not "tweak" it, just remove it and perhaps add a note in the manual
>>> pointing people to the weakref module.
>> 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__?
> Untested, but roughly:
>     _weakrefs = []
>     def _cleanup(ref, handle):
>         _weakrefs.remove(ref)
>         CAPI.close(handle)
>     class BetterWrapper:
>         def __init__(self, *args):
>             handle = self.handle = CAPI.init(*args)
>             _weakrefs.append(
>                 weakref.ref(self,
>                     lambda ref: _cleanup(ref, handle)))
>     def foo(self):
>         CAPI.foo(self.handle)
> There are probably even better ways too, this is just the first that
> comes to mind.

Thanks for the example.

Thus, I believe my example is a good use case for __del__ with no good
enough workaround, which was requested by Micheal in the original post. I
believe that it would be a mistake to remove __del__ unless we provide a
graceful alternative (and I don't consider the code above a graceful
alternative). I still like the __close__ method being proposed. I'd love to
see a PEP for it.
Giovanni Bajo

More information about the Python-3000 mailing list