[PyQt] Hunting down memory leaks

Hans-Peter Jansen hpj at urpla.net
Fri Dec 17 21:35:51 GMT 2010


On Friday 17 December 2010, 22:01:40 Darryl Wallace wrote:
> > Il giorno mar, 14/12/2010 alle 18.02 +0100, Hans Meine ha scritto:
> > > 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] -
> >
> > > h1[k])
> >
> > really useful thanks!
> >
> > Using these functions I found that if I do something like this:
> >
> > self.ui.lineEdit.mouseReleaseEvent=self....
> >
> > I have to manually do:
> >
> > self.ui.lineEdit.mouseReleaseEvent=None
> >
> > to get the widget deleted, this seems a pyqt bug,
>
> I would suggest that it's not a PyQt bug but rather a fundamental way
> that Python does garbage collection.  This would occur with any other
> type of Python object that holds a reference to another type of
> Python object regardless of PyQt or not.

IOW: those who monkey patch might suffer from monkeys ill-bred behavior.

I like monkeys.

Pete


More information about the PyQt mailing list