How to connect to a GObject signal in python, without it keeping a reference to the connecter?

2024/11/2 17:55:39

The problem is basically this, in python's gobject and gtk bindings. Assume we have a class that binds to a signal when constructed:

class ClipboardMonitor (object):def __init__(self):clip = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD)clip.connect("owner-change", self._clipboard_changed)

The problem is now that, no instance of ClipboardMonitor will ever die. The gtk clipboard is an application-wide object, and connecting to it keeps a reference to the object, since we use the callback self._clipboard_changed.

I'm debating how to work around this using weak references (weakref module), but I have yet to come up with a plan. Anyone have an idea how to pass a callback to the signal registration, and have it behave like a weak reference (if the signal callback is called when the ClipboardMonitor instance is out of scope, it should be a no-op).

Addition: Phrased independently of GObject or GTK+:

How do you provide a callback method to an opaque object, with weakref semantics? If the connecting object goes out of scope, it should be deleted and the callback should act as a no-op; the connectee should not hold a reference to the connector.

To clarify: I explicitly want to avoid having to call a "destructor/finalizer" method

Answer

The standard way is to disconnect the signal. This however needs to have a destructor-like method in your class, called explicitly by code which maintains your object. This is necessary, because otherwise you'll get circular dependency.

class ClipboardMonitor(object):[...]def __init__(self):self.clip = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD)self.signal_id = self.clip.connect("owner-change", self._clipboard_changed)def close(self):self.clip.disconnect(self.signal_id)

As you pointed out, you need weakrefs if you want to avoid explicite destroying. I would write a weak callback factory, like:

import weakrefclass CallbackWrapper(object):def __init__(self, sender, callback):self.weak_obj = weakref.ref(callback.im_self)self.weak_fun = weakref.ref(callback.im_func)self.sender = senderself.handle = Nonedef __call__(self, *things):obj = self.weak_obj()fun = self.weak_fun()if obj is not None and fun is not None:return fun(obj, *things)elif self.handle is not None:self.sender.disconnect(self.handle)self.handle = Noneself.sender = Nonedef weak_connect(sender, signal, callback):wrapper = CallbackWrapper(sender, callback)wrapper.handle = sender.connect(signal, wrapper)return wrapper

(this is a proof of concept code, works for me -- you should probably adapt this piece to your needs). Few notes:

  • I am storing callback object and function separatelly. You cannot simply make a weakref of a bound method, because bound methods are very temporary objects. Actually weakref.ref(obj.method) will destroy the bound method object instantly after creating a weakref. I didn't check whether it is needed to store a weakref to the function too... I guess if your code is static, you probably can avoid that.
  • The object wrapper will remove itself from the signal sender when it notices that the weak reference ceased to exist. This is also necessary to destroy the circular dependence between the CallbackWrapper and the signal sender object.
https://en.xdnf.cn/q/72905.html

Related Q&A

openpyxl please do not assume text as a number when importing

There are numerous questions about how to stop Excel from interpreting text as a number, or how to output number formats with openpyxl, but I havent seen any solutions to this problem:I have an Excel s…

NLTK CoreNLPDependencyParser: Failed to establish connection

Im trying to use the Stanford Parser through NLTK, following the example here.I follow the first two lines of the example (with the necessary import)from nltk.parse.corenlp import CoreNLPDependencyPars…

How to convert hex string to color image in python?

im new in programming so i have some question about converting string to color image.i have one data , it consists of Hex String, like a fff2f3..... i want to convert this file to png like this.i can c…

How to add values to a new column in pandas dataframe?

I want to create a new named column in a Pandas dataframe, insert first value into it, and then add another values to the same column:Something like:import pandasdf = pandas.DataFrame() df[New column].…

value error happens when using GridSearchCV

I am using GridSearchCV to do classification and my codes are:parameter_grid_SVM = {dual:[True,False],loss:["squared_hinge","hinge"],penalty:["l1","l2"] } clf = …

How to remove english text from arabic string in python?

I have an Arabic string with English text and punctuations. I need to filter Arabic text and I tried removing punctuations and English words using sting. However, I lost the spacing between Arabic word…

python module pandas has no attribute plotting

I am a beginner of Python. I follow the machine learning course of Intel. And I encounter some troubles in coding. I run the code below in Jupyter and it raises an AttributeError.import pandas as pd st…

pandass resample with fill_method: Need to know data from which row was copied?

I am trying to use resample method to fill the gaps in timeseries data. But I also want to know which row was used to fill the missed data.This is my input series.In [28]: data Out[28]: Date 2002-09-0…

Inefficient multiprocessing of numpy-based calculations

Im trying to parallelize some calculations that use numpy with the help of Pythons multiprocessing module. Consider this simplified example:import time import numpyfrom multiprocessing import Pooldef t…

SQLite: return only top 2 results within each group

I checked other solutions to similar problems, but sqlite does not support row_number() and rank() functions or there are no examples which involve joining multiple tables, grouping them by multiple co…