Some thoughts on garbage collection

"Martin v. Löwis" martin at
Mon Jan 23 16:31:17 EST 2006

Frank Millman wrote:
> In principle I agree. My concern was that I might have inadvertently
> done something wrong (e.g. left a reference dangling) which would
> prevent gc from removing all objects which I wanted to be removed.

Depends on what it really is that you want to know. If you want
to know whether gc can release all garbage objects, you should
look at gc.garbage, after a gc.collect call immediately before
the end of the program.

The issue here is that objects implementing __del__ in a cycle will
never get collected (but added to gc.garbage); this is something
you need to be aware of.

If you want to find out if there are objects which you hold onto
too long, you can look at len(gc.get_objects()) from time to
time. This won't be all objects, but just the container objects.
If you see the number growing over time, you have a leak.

You could then also categorize this by type, e.g.

frequency = {}
for o in gc.get_objects():
    o = o.__class__.__name__
    frequency[o] = frequency.get(o, 0) + 1
print sorted(frequency.iteritems(), key=operator.itemgetter(1),

If you are interested in total object counts, you need to run
the debug version of Python.


More information about the Python-list mailing list