Class destructor

Jp Calderone exarkun at intarweb.us
Thu Feb 13 14:35:58 EST 2003


On Thu, Feb 13, 2003 at 03:46:03PM +0100, Roberto Cavada wrote:
> Hi there,
> [snip - cyclic structure with __del__]
> 
> If I correctly understood, circular references detection is disabled 
> when __del__ method is defined. I guess this is a precise choice, due 
> to the fact that there is no control on what __del__ really does, so 
> it is better wasting of memory than falling into segfaults.

  Not exactly.  The cycles are still detected, even when __del__ is defined
on one object or more objects in the cycle.  The difference is that instead
of being collected and freed, the entire cycle is added to the gc.garbage
list.  There it stays until your program exits, or...

> 
> If it is correct, I think this is a strong restriction, because I 
> cannot control the lifetime of instances.
> 
> What's the solution in this case?

  There are several, at least.  In order of personal preference:

  1) Don't create cycles of objects that implement __del__.

  2) Add a method to the class that implements __del__ that breaks
     the cycle.  Call this method explicitly before you del any variable
     bound to an instance of this class.

  3) Periodically throughout your program's run, inspect the contents of
     gc.garbage.  If it contains cycles containing your objects, break these
     cycles explicitly, and remove the objects from the garbage list. *


  The gc module also has functions for setting the debug level of the
collector, so you can get more information about how your program is
leaking.  I strongly recommend utilizing the first approach, though.

  Jp

[*] I'm not sure if this approach actually work.  The gc may not re-examine
    objects that have already been placed into the garbage list.  Can anyone
    confirm or deny this?

-- 
Getting undefined references to 'crypt' when you compile your mud?
Add `-lcrypt` to the link flags and everything will work fine.
-- 
 up 5 days, 0:28, 3 users, load average: 0.06, 0.16, 0.08
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20030213/dd8d5ff7/attachment.sig>


More information about the Python-list mailing list