【发布时间】:2012-04-20 12:19:08
【问题描述】:
有没有办法从指向它的弱代理中获取原始对象?例如,weakref.proxy() 是否存在相反的情况?
import weakref
class C(object):
def __init__(self, other):
self.other = weakref.proxy(other)
class Other(object):
pass
others = [Other() for i in xrange(3)]
my_list = [C(others[i % len(others)]) for i in xrange(10)]
我需要从my_list 获取唯一other 成员的列表。我喜欢此类任务的方式
是使用set:
unique_others = {x.other for x in my_list}
不幸的是,这会引发TypeError: unhashable type: 'weakproxy'
unique_others = []
for x in my_list:
if x.other in unique_others:
continue
unique_others.append(x.other)
但标题中指出的一般问题仍然存在。
如果我只有 my_list 受到控制,而 others 被埋在某个库中,并且有人可能随时删除它们,我想通过在列表中收集 nonweak 引用来防止删除怎么办?
repr(),而不是<weakproxy at xx to Other at xx>
我想应该有类似weakref.unproxy 我不知道的东西。
【问题讨论】: