Generator inside a class prevent __del__ ??

Andrew Bennetts andrew-pythonlist at puzzling.org
Thu Apr 22 09:05:03 EDT 2004


On Thu, Apr 22, 2004 at 11:12:27AM +0200, Emmanuel wrote:
> 
> Ok, I think I don't understand anything anymore...
> 
> I thought __del__ was the destructor of the object, like the object::~object in C++ ( my
> experience in programming is mainly from C++ ), and so __del__ shouldn't affect when they
> are destructed.

__del__ unfortunately *does* impact the lifetime of the object, at least in
CPython:
    http://docs.python.org/lib/module-gc.html#l2h-403
    http://docs.python.org/ref/customization.html#l2h-175

It's main use used to be to break reference cycles, because before Python
2.0 (or perhaps 1.6?), it couldn't automatically collect reference cycles
because it used a purely ref-count based approach.  Now that cycles are
automatically collected, there's not much point in defining __del__ (and it
can actually have unexpected results).

> And I thought weakref is a way to control the lifetime, ie when the ref count is
> decremented, and when to call __del__.

No -- weakref doesn't affect the lifetime, that's it's point.  It's a way to
have a reference to an object that doesn't keep the object alive if nothing
else is.  As the documentation at
http://docs.python.org/lib/module-weakref.html says:

    A weak reference to an object is not enough to keep the object alive:
    when the only remaining references to a referent are weak references,
    garbage collection is free to destroy the referent and reuse its memory
    for something else.

> >From what you ( and others ) are saying, I'm proven wrong...
> 
> Do you know where I can find more information, beside python doc ?

Try googling for tutorials and things, there's probably stuff out there.
The Python docs are pretty good, though... the weakref module has pretty
comprehensive documentation, and the description of __del__ in the language
reference has big note that mentions that garbage-collection of cycles
doesn't work when __del__ methods are involved.

I've also found books such as Python in a Nutshell and the Python Essential
Reference to be quite good at pointing this sort of thing out, when I've
looked.  I usually rely on the official Python docs, though.

-Andrew.





More information about the Python-list mailing list