of destructors, open files and garbage collection

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Thu May 24 12:20:36 EDT 2007


In <1180021256.619953.80500 at q66g2000hsg.googlegroups.com>, massimo s.
wrote:

> I have a for loop that looks like the following :
> 
> for item in long_list:
>        foo(item)
> 
> def foo(item):
>        item.create_blah() #<--this creates item.blah; by doing that it
> opens a file and leaves it open until blah.__del__() is called
> 
> Now, what I thought is that if I call
> 
> del(item)
> 
> it will delete item and also all objects created inside item.

It will delete the *name* `item`.  It does nothing to the object that was
bound to that name.  If the name was the only reference to that object, it
may be garbage collected sooner or later.  Read the documentation for the
`__del__()` method for more details and why implementing such a method
increases the chance that the object *won't* be garbage collected!

Relying on the `__del__()` method isn't a good idea because there are no
really hard guaranties by the language if and when it will be called.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list