Prevent Signal/Slot memory leaks in python

When using Qt in python, any QObject with a connection to at least one of its signals is not eligible for garbage collection. This makes it very easy to have memory leaks when using dynamically created QWidgets. In order to not leak memory, you must disconnect any slots from all signals on the QObject before dereferencing. Every connect statement returns an object that you can use to disconnect it. So just keep track of all the connections and disconnect them when it is time to dereference the object, right? In theory that is great and all, but it is an absolute pain to implement. Especially considering anything that has ever had reference to the object could have connected something to its signals.

So throwing that solution out, what remains? Well, as it turns out, python has a straightforward way to do object introspection. By examining all the properties of an object, you can determine which are signals. In addition, QObject has a method that returns how many slots are connected to a given signal. The following code uses the above to disconnect all slots from any signals with connections:

for x in filter(lambda y: type(y) == pyqtBoundSignal and 0 < element.receivers(y),
        map(lambda z: getattr(element, z), dir(element))):