I have a project where i’m trying to use weakrefs with callbacks, and I don’t understand what I’m doing wrong. I have created simplified test that shows the exact behavior i’m confused with.
Why is it that in this test test_a works as expected, but the weakref for self.MyCallbackB disappears between the class initialization and calling test_b? I thought like as long as the instance (a) exists, the reference to self.MyCallbackB should exist, but it doesn’t.
import weakref class A(object): def __init__(self): def MyCallbackA(): print 'MyCallbackA' self.MyCallbackA = MyCallbackA self._testA = weakref.proxy(self.MyCallbackA) self._testB = weakref.proxy(self.MyCallbackB) def MyCallbackB(self): print 'MyCallbackB' def test_a(self): self._testA() def test_b(self): self._testB() if __name__ == '__main__': a = A() a.test_a() a.test_b()
You want a WeakMethod.
An explanation why your solution doesn’t work can be found in the discussion of the recipe: