Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I have asked <a href="https://stackoverflow.com/questions/1364923/how-to-connect-to-a-gobject-signal-in-python-without-it-keeping-a-reference-to-t">the same question here</a>! In my question, I talk about GObject, but recognize it is a general problem in any kind of Python! I got help by lioro there, and what I use in my current code is below. Some important points:</p> <ul> <li><p>You can't weakref the method object. You have to weakref the instance and its function attribute, or simply the method name (as I do in my code below)</p></li> <li><p>You can add some mechanism to unregister the callback when your connected object goes away, if you don't do this, you will have the WeakCallback object live on instead, and exectute an empty method when the even occurs.</p></li> </ul> <p>.</p> <pre><code>class WeakCallback (object): """A Weak Callback object that will keep a reference to the connecting object with weakref semantics. This allows object A to pass a callback method to object S, without object S keeping A alive. """ def __init__(self, mcallback): """Create a new Weak Callback calling the method @mcallback""" obj = mcallback.im_self attr = mcallback.im_func.__name__ self.wref = weakref.ref(obj, self.object_deleted) self.callback_attr = attr self.token = None def __call__(self, *args, **kwargs): obj = self.wref() if obj: attr = getattr(obj, self.callback_attr) attr(*args, **kwargs) else: self.default_callback(*args, **kwargs) def default_callback(self, *args, **kwargs): """Called instead of callback when expired""" pass def object_deleted(self, wref): """Called when callback expires""" pass </code></pre> <p>Usage notes:</p> <pre><code># illustration how I typically use it weak_call = WeakCallback(self._something_changed) long_lived_object.connect("on_change", weak_call) </code></pre> <p>I use the <code>WeakCallback.token</code> attribute in subclasses I've made to manage disconnecting the callback when the connecter goes away</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload