有没有办法从弱代理指向它的原始对象?例如,是否存在反转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)]
Run Code Online (Sandbox Code Playgroud)
我需要从中获取唯一other成员列表my_list.我喜欢这种任务的方式是使用set:
unique_others = {x.other for x in my_list}
Run Code Online (Sandbox Code Playgroud)
不幸的是这引发了 TypeError: unhashable type: 'weakproxy'
unique_others = []
for x in my_list:
if x.other in unique_others:
continue
unique_others.append(x.other)
Run Code Online (Sandbox Code Playgroud)
但标题中提到的一般问题仍然存在.如果我只能my_list控制并others在某些lib中埋葬并且有人可能随时删除它们,我想通过在列表中收集非弱引用来防止删除该怎么办?
repr()对象本身,而不是<weakproxy at xx to …