Question about weakref
ian.g.kelly at gmail.com
Fri Jul 6 19:04:06 CEST 2012
On Fri, Jul 6, 2012 at 1:00 AM, Frank Millman <frank at chagford.com> wrote:
> I have investigated a bit further, and now I have a clue as to what is
> happening, though not a full understanding.
> If you use 'b = weakref.ref(obj)', 'b' refers to the weak reference, and
> 'b()' refers to the referenced object.
> If you use 'b = weakref.proxy(obj)', 'b' refers to the referenced object. I
> don't know how to refer to the weak reference itself. In a way that is the
> whole point of using 'proxy', but the difficulty comes when you want to
> remove the weak reference when the referenced object is deleted.
Not quite. 'b' refers to the proxy, which uses magic methods to mimic
the referenced object. It is still a separate object, however. In
fact, I actually think it's not directly possible to refer to the
*referenced object* via a proxy, although there are round-about ways
to accomplish it.
>>> import weakref
>>> class Foo(object): pass
>>> a = Foo()
>>> b = weakref.proxy(a)
>>> a is a
>>> a is b
> The full story is more complicated than that - why does my example work when
> I delete x, then y, then z, but not if I reverse the order?
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 have one suggestion, though: you might try removing the __del__
method from the listener class, as the presence of that method can
interfere with garbage collection in some cases, and it is generally
contra-recommended. I'm not sure why that would affect the code you
posted, but it can't hurt to try it.
More information about the Python-list