[PyQt] Hunting down memory leaks

Hans Meine meine at informatik.uni-hamburg.de
Tue Dec 14 17:02:12 GMT 2010

Am Dienstag 14 Dezember 2010, 17:05:42 schrieb Darryl Wallace:
> One of the things I've found in this regard has to do with Python and
> garbage collection.  If the reference count to certain objects does not go
> to zero then the item will not be garbage collected.
> Ensure that the objects that you want cleaned up have no references to
> them.  I've found that setting widgets' parents to None and then setting
> that variable to None often does the trick.
> Anyone else have tips on garbage collection with PyQt???

I also use sip.delete(obj) or obj.deleteLater() from time to time.

Also I have a large number of helper functions based on the gc module, e.g. 
the ones below.  These are very useful, use like this:

h1 = gcHistogram()
... # some long-running calculations which seem to leak memory
h2 = gcHistogram()
diffHists(h1, h2)

This will output the *types* of objects that have been created in the 
meantime, along with their counts.  Sometimes, this will not help much though, 
e.g. if you use standard python lists a lot.  (It might make sense to use 
specialized classes derived from list anyway, no?)

def gcHistogram():
	"""Returns per-class counts of existing objects."""
	result = {}
	for o in gc.get_objects():
		t = type(o)
		count = result.get(t, 0)
		result[t] = count + 1
	return result

def diffHists(h1, h2):
	"""Prints differences between two results of gcHistogram()."""
	for k in h1:
		if h1[k] != h2[k]:
			print "%s: %d -> %d (%s%d)" % (
				k, h1[k], h2[k], h2[k] > h1[k] and "+" or "", h2[k] - 


More information about the PyQt mailing list