这个问题基本上是这样,在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语义? 如果连接对象超出范围,它应该被删除,回调应无操作行为; 该connectee不应抱到连接器的参考。
为了澄清:我明确希望避免以所谓的“析构函数/终结”的方法
Answer 1:
的标准方法是断开信号。 然而,这需要在你的类中,通过保持你的目标代码显式调用析构函数的类方法。 这是必要的,否则你会得到循环依赖。
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)
正如你指出,你,如果你想避免explicite破坏需要weakrefs。 我会写一个弱回调工厂,如:
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
(这是概念代码证明,工作对我来说 - 你可能要适应这片您的需要)。 几点注意事项:
- 我存储的回调对象和功能separatelly。 你不能简单地做一个绑定方法的weakref,因为绑定方法是非常临时对象。 其实
weakref.ref(obj.method)
将创建一个weakref后立即销毁绑定的方法对象。 我没有检查它是否需要存储weakref的功能太...我想,如果你的代码是静态的,你也许能够避免。 - 对象包装器将当它发现自己的弱引用不复存在本身从信号发送器除去。 这也是必要破坏CallbackWrapper和信号发送器物体之间的圆形的依赖。
Answer 2:
(这个答案跟踪我的进度)
这第二个版本将切断为好; 我有gobjects便利的功能,但我确实需要这个类的一个更普遍的情况 - 无论是d总线讯号回调和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)
Answer 3:
没有真正尝试过,但是:
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))
文章来源: How to connect to a GObject signal in python, without it keeping a reference to the connecter?