小编rob*_*hek的帖子

Python:解除引用weakproxy

有没有办法从弱代理指向它的原始对象?例如,是否存在反转weakref.proxy()

一个简化的例子(python2.7):

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 …

python weak-references

11
推荐指数
3
解决办法
3088
查看次数

标签 统计

python ×1

weak-references ×1