Weakref.ref callbacks and eliminating __del__ methods

Richie Hindle richie at entrian.com
Mon Jan 24 07:59:57 EST 2005


[Tim]
> I'll note that one fairly obvious pattern works very well for weakrefs
> and __del__ methods (mutatis mutandis):  don't put the __del__ method
> in self, put it in a dead-simple object hanging *off* of self.  Like
> the simple:
> 
> class BTreeCloser:
>     def __init__(self, btree):
>         self.btree = btree
> 
>     def __del__(self):
>         if self.btree:
>             self.btree.close()
>             self.btree = None
> 
> Then give self an attribute refererring to a BTreeCloser instance, and
> keep self's class free of a __del__ method.  The operational
> definition of "dead simple" is "may or may not be reachable only from
> cycles, but is never itself part of a cycle".

This is very nice - I've been wondering about just this problem recently,
and this will be very useful.  Many thanks!

One question: why the `self.btree = None` in the last line?  Isn't
`self.btree` guaranteed to go away at this point anyway?  (If the answer
is "it's necessary for weird cases that would take an hour to explain"
then I'll be more than happy to simply use it.  8-)

-- 
Richie Hindle
richie at entrian.com




More information about the Python-list mailing list