[Python-3000] Removing __del__

Raymond Hettinger rhettinger at ewtllc.com
Tue Sep 26 01:41:51 CEST 2006


>>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).
>  
>
ISTM, you've adopted __del__ as your best friend, learned to avoid it 
pitfalls, employed it throughout your code, and forsaken weakref based 
approaches which is understandable because weakrefs came along rather 
ate in the game. I congratulate you on that level of accomplishment.

I support the original suggestion to remove __del__ because I think that 
most programmers would be better-off without it, that weakref-based 
alternatives are possible (though not necessarily easier or more 
succinct), and that explicit finalization is preferable to implicit 
(i.e. there's a reason for advice to wrap file access in a try/finally 
to make sure an explicit close() occurs). 

In a world dominated by new-style classes, it is a strong plus that 
weakrefs reliably avoid creating cycles which subtlely block or delay 
finalization.  Eliminating __del__ will also mean an end to 
implementation headaches relating to issues stemming from arbitrary 
finalization code running while an object is still alive. The __del__ 
special method has long been a dark corner of Python, a rarely used and 
error-prone tool.  Just having it around creates a suggestion that it 
would be a good idea to design code relying on implicit finalization and 
the fragile hope that you or some future maintainer doesn't accidently 
keep a reference to an object you had intended to vanish of its own accord.

In short, __del__ should disappear not because it is useless but because 
it is hazardous.  The consenting adults philosophy means that we don't 
put-up artificial barriers to intentional hacks, but it does not mean 
that we bait the hook and leave error-prone traps for the unwary.  In 
Py3k, I would like to see explicit finalization as a preferred approach 
and for weakrefs be the one-way-to-do-it for designs with implicit 
finalization.


Raymond


More information about the Python-3000 mailing list