weakref list in python
- by Dan
I'm in need of a list of weak references that deletes items when they die. Currently the only way I have of doing this is to keep flushing the list (removing dead references manually).
I'm aware there's a WeakKeyDictionary and a WeakValueDictionary, but I'm really after a WeakList, is there a way of doing this?
Here's an example:
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()