weakref list in python

Posted by Dan on Stack Overflow See other posts from Stack Overflow or by Dan
Published on 2009-03-24T15:39:59Z Indexed on 2010/04/12 22:12 UTC
Read the original article Hit count: 379

Filed under:
|

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()

© Stack Overflow or respective owner

Related posts about python

Related posts about weak-references