Question about weakref
frank at chagford.com
Fri Jul 6 09:00:49 CEST 2012
On 05/07/2012 19:47, Dieter Maurer wrote:
> Frank Millman<frank at chagford.com> writes:
>> I would still like to know why weakref.proxy raised an exception. I
>> have re-read the manual several times, and googled for similar
>> problems, but am none the wiser.
> In fact, it is documented. Accessing a proxy will raise an exception
> when the proxied object no longer exists.
> What you can ask is why your proxy has been accessed after the
> object was deleted. The documentation is specific: during the callback,
> the object should still exist. Thus, apparently, one of your proxies
> outlived an event that should have deleted it (probably a hole in
> your logic).
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.
This is from the manual section on weakref.ref -
"If callback is provided and not None, and the returned weakref object
is still alive, the callback will be called when the object is about to
be finalized; the weak reference object will be passed as the only
parameter to the callback; the referent will no longer be available."
My callback method looks like this -
It successfully removes the weak reference from self.array.
This is from the manual section on weakref.proxy -
"callback is the same as the parameter of the same name to the ref()
My callback method looks the same. However, although 'b' is the weak
reference, when I refer to 'b' it refers to the original object, which
at this stage no longer exists.
So my revised question is -
How can you remove the weak reference if you use proxy?
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?
However, I think that I have isolated the fundamental reason. So any
comments on my latest findings will be appreciated.
More information about the Python-list