[Python-3000] Removing __del__
Giovanni Bajo
rasky at develer.com
Sat Sep 23 11:39:20 CEST 2006
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).
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.
Giovanni Bajo
[1] tempfile.NamedTemporaryFile can't always be used because it does not
guarantee that the file can be reopened; for instance, zipfile.Zipfile() wants
a filename, so if you want to create a temporary ZipFile you can't use
tempfile.NamedTemporaryFile.
More information about the Python-3000
mailing list