18

我需要一个弱引用列表,当它们死亡时删除它们。目前我这样做的唯一方法是继续刷新列表(手动删除死引用)。

我知道有一个 WeakKeyDictionary 和一个 WeakValueDictionary,但我真的很喜欢 WeakList,有没有办法做到这一点?

这是一个例子:

import weakref

class A(object):
    def __init__(self):
       pass

class B(object):
    def __init__(self):
        self._references = []

    def addReference(self, obj):
        self._references.append(weakref.ref(obj))

    def flush(self):
        toRemove = []

        for ref in self._references:
            if ref() is None:
                toRemove.append(ref)

        for item in toRemove:
            self._references.remove(item)

b = B()

a1 = A()
b.addReference(a1)
a2 = A()
b.addReference(a2)

del a1
b.flush()
del a2
b.flush()
4

6 回答 6

6

您可以自己实现它,类似于您的做法,但使用flush()在尝试访问项目之前调用的列表子类。

显然,您不想在每次访问时都这样做,但是您可以通过在弱引用上设置回调来优化此操作,以便在某些事情死亡时将列表标记为脏。然后,您只需要在自上次访问后发生某些事情时刷新列表。

这是使用此方法实现的列表类。(请注意,它没有经过太多测试,并且某些方法的实现效率不高(例如,那些只是转换为真实列表并在其上调用方法的方法),但这应该是一个合理的起点:

import weakref

class WeakList(list):
    def __init__(self, seq=()):
        list.__init__(self)
        self._refs = []
        self._dirty=False
        for x in seq: self.append(x)

    def _mark_dirty(self, wref):
        self._dirty = True

    def flush(self):
        self._refs = [x for x in self._refs if x() is not None]
        self._dirty=False

    def __getitem__(self, idx):
        if self._dirty: self.flush()
        return self._refs[idx]()

    def __iter__(self):
        for ref in self._refs:
            obj = ref()
            if obj is not None: yield obj

    def __repr__(self):
        return "WeakList(%r)" % list(self)

    def __len__(self):
        if self._dirty: self.flush()
        return len(self._refs)

    def __setitem__(self, idx, obj):
        if isinstance(idx, slice):
            self._refs[idx] = [weakref.ref(obj, self._mark_dirty) for x in obj]
        else:
            self._refs[idx] = weakref.ref(obj, self._mark_dirty)
        
    def __delitem__(self, idx):
        del self._refs[idx]

    def append(self, obj):
        self._refs.append(weakref.ref(obj, self._mark_dirty))

    def count(self, obj):
        return list(self).count(obj)

    def extend(self, items):
        for x in items: self.append(x)
        
    def index(self, obj):
        return list(self).index(obj)
    
    def insert(self, idx, obj):
        self._refs.insert(idx, weakref.ref(obj, self._mark_dirty))
        
    def pop(self, idx):
        if self._dirty: self.flush()
        obj=self._refs[idx]()
        del self._refs[idx]
        return obj

    def remove(self, obj):
        if self._dirty: self.flush() # Ensure all valid.
        for i, x in enumerate(self):
            if x == obj:
                del self[i]
        
    def reverse(self):
        self._refs.reverse()

    def sort(self, cmp=None, key=None, reverse=False):
        if self._dirty: self.flush()
        if key is not None:
            key = lambda x,key=key: key(x())
        else:
            key = apply
        self._refs.sort(cmp=cmp, key=key, reverse=reverse)

    def __add__(self, other):
        l = WeakList(self)
        l.extend(other)
        return l

    def __iadd__(self, other):
        self.extend(other)
        return self
        
    def __contains__(self, obj):
        return obj in list(self)

    def __mul__(self, n):
        return WeakList(list(self)*n)
        
    def __imul__(self, n):
        self._refs *= n
        return self
于 2009-03-24T17:08:36.773 回答
5

您可以使用WeakSet同一个weakref 模块(顺便说一句,它实际上是在其他地方定义的,但它是在那里导入的)。

>>> from weakref import WeakSet
>>> s = WeakSet()
>>> class Obj(object): pass # can't weakref simple objects
>>> a = Obj()
>>> s.add(a)
>>> print len(s)
1
>>> del a
>>> print len(s)
0
于 2011-06-07T22:52:26.227 回答
5

因为我需要像你这样的弱引用列表,所以我制作了一个并将其发布在 pypi 上。

现在你可以这样做:

pip install weakreflist

然后:

from weakreflist import WeakList
于 2012-11-21T05:06:19.997 回答
3

为什么你不能这样做:

import weakref

class WeakList(list):
    def append(self, item):
        list.append(self, weakref.ref(item, self.remove))

__iadd__然后对等做类似的extend事情。对我有用。

于 2010-04-12T22:09:36.393 回答
0

使用传递给弱引用的第二个参数的回调函数。

这段代码应该起作用:

import weakref

class WeakRefList(list):

    def add_reference(self, obj):
        self._references.append(weakref.proxy(obj, self.remove))
于 2012-11-15T20:44:50.897 回答
0

你打算如何使用B?我对我构建的弱引用列表所做的唯一事情就是迭代它,所以它的实现很简单:

import weakref

class WeakRefList(object):
    "weakref psuedo list"
    def __init__(yo):
        yo._items = list()
    def __iter__(yo):
        yo._items = [s for s in yo._items if s() is not None]
        return (s() for s in yo._items if s() is not None)
    def __len__(yo):
        yo._items = [s for s in yo._items if s() is not None]
        return len(yo._items)
    def append(yo, new_item):
        yo._items.append(weakref.ref(new_item))
        yo._items = [s for s in yo._items if s() is not None]
于 2011-10-31T19:43:32.467 回答