Re: python classes and signal connects
- From: Simon Feltman <s feltman gmail com>
- To: Thomas Bechtold <thomasbechtold jpberlin de>
- Cc: python-hackers-list gnome org
- Subject: Re: python classes and signal connects
- Date: Mon, 1 Oct 2012 13:44:57 -0700
Hi Thomas,
It would help to give some context as to what you are trying to
accomplish with having a class. In the example the TestSignals class
is superfluous "t = TestSignals()" could be replaced with the contents
of __init__ and the callback could be moved out as a standalone
function. But I gather what you are actually trying to do is more
complex than this?
The specific issue you are seeing is because the callback connected to
the signal is a bound method: "self.button_clicked_cb". A bound method
will keep a reference to the instance of its class TestSignals and the
function. This can be observed as follows:
test = TestSignals()
test.button_clicked_cb.__self__ == test # True
If button_clicked_cb does not access any state on the TestSignals
instance, than by all means it should be moved outside of the class or
made into a staticmethod or classmethod.
-Simon
On Sat, Sep 29, 2012 at 3:32 AM, Thomas Bechtold
<thomasbechtold jpberlin de> wrote:
>
> Hi,
>
> I created a python (new style) class which contains a Gtk.Button and a
> callback function which is connected to the "clicked" signal:
>
> class TestSignals(object):
> def __del__(self):
> print "Deleted object"
>
> def __init__(self):
> self.button = Gtk.Button("My Button")
> self.button.connect("clicked", self.button_clicked_cb)
>
> def button_clicked_cb(self, button, user_data):
> print "button clicked"
>
>
>
> When I create instances of this class in a loop, the objects are never
> destroyed (I never see "Deleted object" on the terminal and the memory
> consumption increase):
>
> if __name__ == "__main__":
> gc.collect()
>
> for i in range(0, 500):
> t = TestSignals()
> gc.collect()
>
> print "instance generation finished (count: %s)" % (i)
> gc.collect()
> raw_input("press enter to exit ...")
>
>
> I can move the button_clicked_cb() function outside of the class (and
> remove the "self" parameter) and then the instances will be destroyed.
>
> Is this the correct way to handle this? Or is there something wrong with
> pyi? Imho the callback should be inside of the class.
>
>
> Cheers,
>
>
> Tom
>
> _______________________________________________
> python-hackers-list mailing list
> python-hackers-list gnome org
> https://mail.gnome.org/mailman/listinfo/python-hackers-list
[Date Prev][
Date Next] [Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]