craneium.net

brain matters . . .

  • Increase font size
  • Default font size
  • Decrease font size
Home Python Programming Python's __del__ Function

Python's __del__ Function

E-mail Print PDF

I had seen people use Python's __del__ method in classes, but upon using it myself, I discovered it is very broken.  See the following:

from scipy import *

import time

class Bork:

def __init__(self):

print "I'm Alive"

def __del__(self):

print "I'm Dead"

raise ValueError("WTF")

 

b = Bork()

del b

print "I am undead"

Which results in the following:
meawoppl@leeloo:~/ndsolver/ndsolver$ python what.py
I'm Alive
I'm Dead
Exception ValueError: ValueError('WTF',) in <bound method Bork.__del__ of 
<__main__.Bork instance at 0x1db2878>> ignored
I am undead
Exceptions in the desctuctor just get printed to the standard error?  Alright, although this is documented it is a pretty serious departure from typical Python described here:

 

Due to the precarious circumstances under which __del__() methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to sys.stderrinstead. Also, when __del__() is invoked in response to a module being deleted (e.g., when execution of the program is done), other globals referenced by the __del__() method may already have been deleted or in the process of being torn down (e.g. the import machinery shutting down). For this reason, __del__() methods should do the absolute minimum needed to maintain external invariants. Starting with version 1.5, Python guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted; if no other references to such globals exist, this may help in assuring that imported modules are still available at the time when the __del__() method is called.

So in summary:

1.) __del__ may  or may not have access to methods of the class.

2.) __del__ methods have an implicit try/except/print so exceptions can not be handled externally.

3.) Don't use this method if you can avoid it!

Last Updated on Friday, 15 January 2010 16:21