6

在 python 的 gobject 和 gtk 绑定中,问题基本上是这样的。假设我们有一个在构造时绑定到信号的类:

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

现在的问题是,ClipboardMonitor 的任何实例都不会死掉。gtk 剪贴板是一个应用程序范围的对象,连接到它会保留对该对象的引用,因为我们使用回调self._clipboard_changed

我正在讨论如何使用弱引用(weakref 模块)来解决这个问题,但我还没有想出一个计划。任何人都知道如何将回调传递给信号注册,并让它表现得像一个弱引用(如果在 ClipboardMonitor 实例超出范围时调用信号回调,它应该是无操作的)。

补充:独立于 GObject 或 GTK+ 的措辞:

如何为不透明对象提供回调方法,具有弱引用语义?如果连接对象超出范围,则应将其删除,并且回调应充当空操作;连接者不应持有对连接器的引用。

澄清一下:我明确希望避免调用“析构函数/终结器”方法

4

3 回答 3

10

标准方法是断开信号。然而,这需要在你的类中有一个类似析构函数的方法,由维护你的对象的代码显式调用。这是必要的,否则你会得到循环依赖。

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)

正如您所指出的,如果您想避免显式破坏,则需要弱引用。我会写一个弱回调工厂,比如:

import weakref

class 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 = sender
        self.handle = None

    def __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 = None
            self.sender = None

def weak_connect(sender, signal, callback):
    wrapper = CallbackWrapper(sender, callback)
    wrapper.handle = sender.connect(signal, wrapper)
    return wrapper

(这是一个概念验证代码,对我有用——您可能应该根据您的需要调整这部分)。几点注意事项:

  • 我分别存储回调对象和函数。您不能简单地对绑定方法进行弱引用,因为绑定方法是非常临时的对象。实际上weakref.ref(obj.method)会在创建弱引用后立即销毁绑定的方法对象。我也没有检查是否需要将弱引用存储到函数中......我想如果你的代码是静态的,你可能可以避免这种情况。
  • 当对象包装器注意到弱引用不再存在时,它会将自己从信号发送器中移除。这对于破坏 CallbackWrapper 和信号发送者对象之间的循环依赖也是必要的。
于 2009-09-01T22:27:56.683 回答
1

(这个答案跟踪我的进度)

第二个版本也将断开连接;我有一个用于 gobjects 的便利函数,但实际上我需要这个类来处理更一般的情况——用于 D-Bus 信号回调和 GObject 回调。

无论如何,什么可以称为WeakCallback实现风格?它是对弱回调的非常干净的封装,但不明显地添加了 gobject/dbus 专业化。胜过为这两种情况编写两个子类。

import weakref

class WeakCallback (object):
    """A Weak Callback object that will keep a reference to
    the connecting object with weakref semantics.

    This allows to connect to gobject signals without it keeping
    the connecting object alive forever.

    Will use @gobject_token or @dbus_token if set as follows:
        sender.disconnect(gobject_token)
        dbus_token.remove()
    """
    def __init__(self, obj, attr):
        """Create a new Weak Callback calling the method @obj.@attr"""
        self.wref = weakref.ref(obj)
        self.callback_attr = attr
        self.gobject_token = None
        self.dbus_token = None

    def __call__(self, *args, **kwargs):
        obj = self.wref()
        if obj:
            attr = getattr(obj, self.callback_attr)
            attr(*args, **kwargs)
        elif self.gobject_token:
            sender = args[0]
            sender.disconnect(self.gobject_token)
            self.gobject_token = None
        elif self.dbus_token:
            self.dbus_token.remove()
            self.dbus_token = None

def gobject_connect_weakly(sender, signal, connector, attr, *user_args):
    """Connect weakly to GObject @sender's @signal,
    with a callback in @connector named @attr.
    """
    wc = WeakCallback(connector, attr)
    wc.gobject_token = sender.connect(signal, wc, *user_args)
于 2009-09-01T23:20:06.517 回答
1

实际上还没有尝试过,但是:

class WeakCallback(object):
    """
    Used to wrap bound methods without keeping a ref to the underlying object.
    You can also pass in user_data and user_kwargs in the same way as with
    rpartial. Note that refs will be kept to everything you pass in other than
    the callback, which will have a weakref kept to it.
    """
    def __init__(self, callback, *user_data, **user_kwargs):
        self.im_self = weakref.proxy(callback.im_self, self._invalidated)
        self.im_func = weakref.proxy(callback.im_func)
        self.user_data = user_data
        self.user_kwargs = user_kwargs

    def __call__(self, *args, **kwargs):
        kwargs.update(self.user_kwargs)
        args += self.user_data
        self.im_func(self.im_self, *args, **kwargs)

    def _invalidated(self, im_self):
        """Called by the weakref.proxy object."""
        cb = getattr(self, 'cancel_callback', None)
        if cb is not None:
            cb()

    def add_cancel_function(self, cancel_callback):
        """
        A ref will be kept to cancel_callback. It will be called back without
        any args when the underlying object dies.
        You can wrap it in WeakCallback if you want, but that's a bit too
        self-referrential for me to do by default. Also, that would stop you
        being able to use a lambda as the cancel_callback.
        """
        self.cancel_callback = cancel_callback

def weak_connect(sender, signal, callback):
    """
    API-compatible with the function described in
    http://stackoverflow.com/questions/1364923/. Mostly used as an example.
    """
    cb = WeakCallback(callback)
    handle = sender.connect(signal, cb)
    cb.add_cancel_function(WeakCallback(sender.disconnect, handle))
于 2009-11-12T23:30:29.877 回答