does python have useless destructors?

Duncan Booth me at privacy.net
Fri Jun 11 04:05:07 EDT 2004


"Roger Binns" <rogerb at rogerbinns.com> wrote in news:f10np1-
mbq.ln1 at home.rogerbinns.com:

> Duncan Booth wrote:
>> def f(filename):
>>    dispose infile, outfile
>>
>>    infile = file(filename, "r")
>>    outfile = file(filename+".out", "w")
>>    outfile.write(infile.read())
> 
> While that looks nice, the real problem I have with it is that
> the caller/consumer of objects has to know that they need
> disposing.  For example they have to know that strings don't
> need to be disposed of but files do.  And then things get
> really complicated with toolkits.  For example in a graphical
> toolkit do windows, device contexts, colours, brushes etc
> have to be disposed of?
> 
> The correct answer of course is that the object itself
> should be aware that it needs to be disposed of and that
> real world resources can leak if it isn't.
> 

The object itself can know that it needs to be safely disposed of, but it 
cannot tell *when* to dispose of itself. My example function might create 
multiple objects some of which need disposing when the function returns, 
and others have a longer lifetime. The choice between disposing at the end 
of the function or when some containing object is disposed has to be one 
for the caller.

Taking your graphical toolkit example, the caller shouldn't need to care 
whether each of those objects *needs* disposing, but they should be able to 
control when it happens. That is why Robert Brewer's function works well, 
you can tell it to dispose of an object and if the object doesn't have 
__dispose__ as a method it simply ignores it.



More information about the Python-list mailing list