[Python-3000] PEP: Eliminate __del__

Nick Coghlan ncoghlan at gmail.com
Sat May 5 12:12:36 CEST 2007

Michael Bayer wrote:
> i just dont understand why such an important feature would have to be  
> relegated to just a "recipe".  i think thats a product of the notion  
> that "implicit finalizers are bad, use try/finally".  thats not  
> really valid for things like buffers that flush and database/network  
> connections that must be released when they fall out of scope.

Implicit finalizers are typically bad because they don't provide any 
kind of guarantee as to when they're going to be executed - all they 
promise is "eventually, maybe". If the gc is paused or disabled for some 
reason, the answer is quite possibly never (and with current __del__ 
semantics, the answer in CPython may be never even when full gc is running).

It's just a quirk of CPython that "eventually" normally translates to 
"when the variable goes out of scope" for objects that don't participate 
in cycles.

Accordingly, anything which requires explicit finalization (such as 
flushing a buffer, or releasing a database connection) needs to migrate 
towards using the context management protocol and the with statement to 
ensure things are cleaned up properly regardless of the GC semantics 
that currently happen to be in force.

Implicit finalization still has a place though, and it is curently 
supported in a far more definite fashion by using a weakref callback and 
leaving __del__ undefined. The downside is that the current weakref 
module leaves you with some extra work to do before you can easily use 
it for finalization.

The reason for initially pursuing a recipe approach for weakref based 
finalisation is that it allows time to determine whether or not there 
are better recipes than whatever is proposed in the PEP before casting 
it in the form of fixed language syntax. Adding syntactic sugar for a 
recipe is child's play compared to trying to get rid of syntax (or 
change its semantics) after discovering it is broken in some fashion.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-3000 mailing list