I wrote something like this today (not much different from the mpl_connect documentation:
class Foo(object): def __init__(self): print 'init Foo', self def __del__(self): print 'del Foo', self def callback(self, event=None): print 'Foo.callback', self, event from pylab import * fig = figure() plot(randn(10)) cid = fig.canvas.mpl_connect('button_press_event', Foo().callback) show()
It looks reasonable, but it will not work - as if matplotlib is losing track of the function that I gave it. If instead of passing Foo().callback pass it to lambda e: Foo().callback(e) , it works. Similarly, if I say x = Foo() and then pass it to x.callback , it works.
My presumption is that the nameless instance of Foo created by Foo() is immediately destroyed after the mpl_connect line, that matplotlib, having the Foo.callback link, does not save Foo live. It's right?
In the non-toy code I came across, the solution x = Foo() does not work, apparently because in this case show() was in a different place, so x went out of scope.
In general, Foo().callback is a <bound method Foo.callback of <__main__.Foo object at 0x03B37890>> . My main surprise is that it looks like the related method does not actually support an object reference. It is right?
source share