Suppose I have an object and want one of its methods to be executed when a PyQt signal is emitted. And suppose I want it to do so with a parameter that is not passed by the signal. So I create a lambda as the signal's slot:
class MyClass(object):
def __init__(self, model):
model.model_changed_signal.connect(lambda: self.set_x(model.x(), silent=True))
Now, normally with PyQt signals and slots, signal connections don't prevent garbage collection. When a connected slot's object is garbage collected, the slot will no longer be called when the corresponding signal is emitted.
However, how does this work when using lambdas? I don't store a reference to the lambda, yet the signal-slot connection does keep working. So the lambda is not garbage collected.
If I now set the instance of MyClass
to None
, that instance is not garbage collected either: emitting the model_changed_signal
still executes the lambda succesfully. So apparently, a reference to the instance of MyClass
is kept around somewhere (maybe in the context of the lambda?) - which I don't want.
Why does this happen?
model.model_changed_signal.connect(ModelListener().handle_signal)
, the instance ofModelListener
is garbage collected, andhandle_signal
will never be called. – Humpy