问题基本上就是这个,在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 +的短语:
如何使用weakref语义为不透明对象提供回调方法?如果连接对象超出范围,则应将其删除,并且回调应作为无操作;连接器不应该持有对连接器的引用。
澄清:我明确地希望避免必须调用“析构函数/终结器”方法
答案 0 :(得分:8)
标准方法是断开信号。然而,这需要在类中使用类似析构函数的方法,由维护对象的代码显式调用。这是必要的,因为否则你会得到循环依赖。
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)
会在创建weakref后立即销毁绑定的方法对象。我没有检查是否需要将weakref存储到函数中...我猜如果你的代码是静态的,你可能可以避免这种情况。答案 1 :(得分: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)
答案 2 :(得分: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))