[Python-3000] Removing __del__

Bob Ippolito bob at redivi.com
Sat Sep 23 19:18:25 CEST 2006


On 9/23/06, Giovanni Bajo <rasky at develer.com> wrote:
> Bob Ippolito wrote:
>
> >> class Wrapper2:
> >>    def __init__(self, *args):
> >>         self.handle = CAPI.init(*args)
> >>
> >>    def foo(self):
> >>         CAPI.foo(self.handle)
> >>
> >>    def restart(self):
> >>         self.handle = CAPI.restart(self.handle)
> >>
> >>    def close(self):
> >>         CAPI.close(self.handle)
> >>         self.handle = None
> >>
> >>    def __del__(self):
> >>          if self.handle is not None:
> >>                 self.close()
> >
> > I've never seen an API that works like that. Have you?
>
> The class above shows a case where:
>
> 1) There's a way to destruct the handle BEFORE __del__ is called, which would
> require killing the weakref / deregistering the finalization hook. I believe
> you agree that this is pretty common (I've around 10 usages of this pattern,
> __del__ with a separate explicit closure method, in one Python base-code of
> mine).

Easy enough, that would be a second function and the dict would change a bit.

> 2) The objects required in the destructor can be mutated / changed during the
> lifetime of the instance. For instance, a class that wraps Win32
> FindFirstFirst/FindFirstNext and support transparent directory recursion needs
> something similar. Or CreateToolhelp32Snapshot() with the Module32First/Next
> stuff. Another example is a class which creates named temporary files and needs
> to remove them on finalization. It might need to create several different
> temporary files (say, self.handle is the filename in that case)[1], so the
> filename needed in the destructor changes during the lifetime of the instance.
>
> #2 is admittedly more convoluted (and probably more rare) than #1, but it's
> still a reasonable use case which really you can't easily do with a simple
> finalization API like the one you were proposing. Python is turing-complete
> without __del__, but in some cases the alternatives are *really* worse.

You can of course easily do this with a simple finalization API.
Supporting this simply requires that multiple cleanup functions be
allowed per object.

-bob


More information about the Python-3000 mailing list