Question about weakref

Ian Kelly ian.g.kelly at gmail.com
Fri Jul 6 13:48:36 EDT 2012


On Fri, Jul 6, 2012 at 11:04 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On that, I'm really not sure.  I tried to reproduce the problem
> locally and wasn't able to.  What build of Python are you using, and
> on what platform?

I spoke too soon, I am able to reproduce it.  I think what's going on
here is that when you try to remove the proxy from the list, the
list.remove() call searches for the object by *equality*, not by
identity.  The problem is that at the time of the callback, the
referent is no longer available to implement the equality test, as
noted in the weakref.ref() documentation.  As long as the proxy
happens to be the first element of the list, this is not a problem,
because the proxy evidently short-circuits self == self to return
True.  If it's not the first element of the list, though, then the
first comparison compares the proxy to some other object, and the
proxy raises an exception, because without the referent it no longer
knows how to compare.  If you change your del_b() method to the
following, though, it works:

    def del_b(self, b):
        for i, x in enumerate(self.array):
            if b is x:
                del self.array[i]

This works because it carefully only handles the proxy object itself
and no longer relies on any aspect of the referent for deletion.  It's
not a problem for weakref.ref, because ref objects require an explicit
dereferencing step to access the referent.

Cheers,
Ian



More information about the Python-list mailing list