[PyQt] Lambdas, Closures and Garbage Collection
Phil Thompson
phil at riverbankcomputing.com
Fri Sep 5 09:37:40 BST 2008
On Wed, 03 Sep 2008 15:27:19 +0200, charles matthew chen
<charles.chen at temboo.com> wrote:
>
> Hi Phil,
>
> Thanks for getting back to us.
>
> On Tue, Sep 2, 2008 at 11:09 PM, Phil Thompson
> <phil at riverbankcomputing.com> wrote:
> > You want to force programmers to keep an explicit reference to a
> lambda?
> > That rather misses the point doesn't it?
>
> Yes, however, this behavior is a serious source of memory leaks and
> worse for our project.
>
> Let's say the lambda calls a bound method of an instance - that
> instance and everything it has a strong reference to will never be
> garbage collected. We could explicitly disconnect the lambda/closure
> from the signal, but that too would require us to maintain an explicit
> reference to whatever callable we're using as a slot.
>
> That is, my understanding is this: if you connect a lambda A as a
> slot on a signal of QObject B, and lambda A references instance C, C
> will not be garbage collected until QObject B is deleted/gc'd.
>
> Actually, I'm not 100% sure yet, but I'm working on isolating a bug
> wherein even in the case that B is deleted and gc'd, lambda A (and hence
> instance C) are not garbage collected. If I can confirm, I'll post a
> short snippet that reproduces this issue to the list.
>
> On Tue, Sep 2, 2008 at 11:09 PM, Phil Thompson
> <phil at riverbankcomputing.com> wrote:
> > Probably.
>
> I've looked at the source of SIP and not sure how to go about making
> this patch. sipConnectRx() and sipDisconnectRx() are a bit complex.
> Can you give us any guidance on the best way to go about this?
Not easily - partly because I don't think the idea is a good one. In fact,
at some point, connect will take a strong reference to any slot (not just
non-methods). The reason for the current distinction is historical.
When the code was first written (without support for lambdas and partials)
the cyclic garbage collector didn't exist. I will eventually get around to
making sure the data structures supporting method slots work with the
collector - at which point strong references can be taken.
Phil
More information about the PyQt
mailing list