Decent way to trace resource leaks?

Edward K. Ream edreamleo at charter.net
Wed Mar 24 13:03:13 CET 2004


While you are waiting for the book to be written, here is a simple hack that
can be useful:

# WARNING: the id trick is flawed: newly allocated objects can have the same
address as old objects.

global lastObjectsDict
objects = gc.get_objects()

newObjects = [o for o in objects if not lastObjectsDict.has_key(id(o))]

lastObjectsDict = {}
for o in objects:
 lastObjectsDict[id(o)]=o

As noted in the comment, this has a flaw, but so what?  It will show you
most of what has been allocated since the last time the code was executed.
Naturally, you will put this code in a function of some kind...

I think you will find that relatively simple traces, if called in judicious
places, will be highly effective in finding out most of what is going on in
even a complex app.  You know more about your app than any general tool
possibly can: use that knowledge!

The easiest way to increase the signal-to-noise ratio in traces is to use
strategies that are unique to your app.  For example, rather than trying to
"perfect" the code above in general, you can specialize the code to trace
your app's most important data in a format that is most useful to you.

Edward
--------------------------------------------------------------------
Edward K. Ream   email:  edreamleo at charter.net
Leo: Literate Editor with Outlines
Leo: http://webpages.charter.net/edreamleo/front.html
--------------------------------------------------------------------







More information about the Python-list mailing list