Problem with __del__

Remco Gerlich scarblac at pino.selwerd.nl
Wed Jan 10 08:03:56 EST 2001


Joel Ricker <joejava at dragonat.net> wrote in comp.lang.python:
> I guess I could chime in with my question.  What is the proper
> implementation of deleting objects once you are done with them.  Thats
> probably the one part of the objects section of the tutorial  that I wasn't
> sure about. Wouldn't you want a destructor to do things for cleanup or would
> just implement it differently like this:
> 
> def deleteme(self)
>     dosomething();
>     del self

The 'del self' here does nothing. All that del does is delete the name
self from the local namespace, but that would have happened anyway at the
end of the function. If another variable somewhere still has a reference
to the object, it's not deleted.

Python keeps track of the amount of references that exist to an object. If
this reaches 0, the object is deleted. Although the current implementation
calls __del__ then, this is not guaranteed. It's better to do any cleanup
you need explicitly (but there's no need to free memory and so on, that is
automatic).

A thing to watch out for is cyclical references. If two objects keep
references to each other, or there is a larger ring of objects so you
can go in circles following the references, then they will never be
destroyed by this mechanism. Python 2.0 has an optional garbage collector
which will find isolated groups like this and delete them, but it doesn't
call __del__ when it does (since it's not possible to determine a good order
to call them in).

You don't usually need a lot of cleanup, but if you do it's best to do it
explicitly - that's more readable as well, of course :).

-- 
Remco Gerlich





More information about the Python-list mailing list