__del__ not called?

Duncan Booth duncan.booth at invalid.invalid
Mon Mar 13 10:10:06 CET 2006

Gregor Horvath wrote:

>> Of course, if your __del__ method actually does get invoked during
>> program exit you have to be pretty careful what you do: the chances
>> are any global variables you used in __del__ have already been
>> destroyed in particular any modules you imported may have been
>> deleted. In short, don't rely on anything much being possible from
>> __del__ called this way. 
> I wanted to close a database connection, which is opend by __init__.
> But what happens to my database connection (instance attributes of A) 
> when __del__ is never called?

First off, never depend on __del__ to do anything critical. The only 
guarantee about the __del__ method on an object is that it will be called 
zero, one, or more times. (Admittedly you have to work a bit to get it 
called more than once.)

If you have a resource which absolutely must be tidied up, then always put 
the code which accesses that resource inside a try..finally construct. If 
it is something pretty global to your program than that try..finally might 
have to be at the outermost level of your program:


(In Python 2.5 you will be able to use a 'with' construct instead, but 
unfortunately we still have to wait a bit for that to become common usage).

Without knowing more about the specific database connection, I can't tell 
you what happens if you don't explicitly close it. I would hope that it 
will tidy itself up, but if your code keeps anything cached locally to be 
written out then obviously that might not get written.

If the database supports transactions (and it should), then I would expect 
anything modified in a transaction which has been commited will be written 
correctly, and everything modified in a transaction which has not been 
commited will be discarded: closing (or not) the database should be pretty 
well irrelevant.

More information about the Python-list mailing list