__del__ methods
Robert Rawlins
robert.rawlins at thinkbluemedia.co.uk
Sat Jul 19 10:46:34 EDT 2008
Hi Duncan,
> That sounds like an appropriate use for __del__: it won't matter that it
> may not be called when your app exits.
Ok, well that's good to know. :-)
> Yes, but there is an easy work-around. If you want to track destruction of
> objects of type C then don't add a __del__ method to the C objects.
Instead
> create a separate class which does nothing but track it's own desctruction
> and reference that from the class which may be leaking.
>
> >>> class Track(object):
> def __init__(self, parent):
> self.parentid = id(parent)
> self.parenttype = type(parent).__name__
> def __del__(self):
> print "Destroyed <%s object at %s>" % (self.parenttype,
> self.parentid)
>
>
> >>> class C(object):
> def __init__(self):
> self._track = Track(self)
>
I like this idea, I can definitely see the benefits to working with this
concept. One things I will take this quick opportunity to ask, even though
it's a little OT:
What is the benefit of extending the base 'object' class? What does that
give me that en empty, non subclassed object doesn't?
> However you should also consider that __del__ only lets you log when
> objects are destroyed. Using weak references may be a more useful option
as
> it will let you track which objects are not being destroyed: you can
easily
> keep a dictionary of weak references to all existing objects of interest.
> Check its length periodically to see whether objects are being leaked and
> then inspect the objects themselves to see which ones have leaked.
>
> You can use gc.get_referrers() to find everything that references a
> particular objects and gradually trace backwards until you find the
problem
> reference (it is tricky though as any code which does this needs to ignore
> its own references to the object in question).
Yes, that's a very nice concept and like you say gives you quite a nice
visual reference of what objects are and aren't being destroyed.
Cheers Duncan,
Robert
More information about the Python-list
mailing list