Questions about weakref
Frank Millman
frank at chagford.com
Tue Oct 16 05:10:28 EDT 2018
Hi all
I have some questions about using weakrefs.
My first question is whether weakrefs are the correct tool for my situation.
My use-case is not mentioned in the docs, so maybe it is not intended to be
used this way.
I have a lot of objects active in my app. Some of them (A) are fairly
long-lived. Others (B) are short-lived, but hold a reference to one of the A
objects. For the lifetime of the existence of B, it needs to be notified of
any change of state of A. Therefore when B is created, it adds itself to a
list maintained by A. It adds a tuple consisting of itself and a function
(C). Whenever A detects a change of state, it iterates through the list and
calls the function C, passing B as an argument.
I have quite a bit of additional housekeeping to perform to ensure that,
when B goes out of scope, it removes itself from the list in A. I was hoping
to use weakrefs to make this automatic. So the first question is, is this a
reasonable use of weakrefs?
If yes, my second question is how to guard against A calling methods using
dead B objects, as A has no control over when B might be gc'd.
My thinking is to use a WeakKeyDictionary, with the B object as the key and
the C function as the data.
When A detects a change of state, instead of iterating over the keys, it
should call keyrefs() to get the weakrefs and iterate over that. For each
weakref it should 'call' it to get the actual key, and check for None to
ensure that it is still alive. Does that sound safe?
Incidentally, the docs are slightly misleading. It says that the method
keyrefs returns 'an iterable of the weak references to the keys'. I was not
sure if that would expose me to the 'change size while iterating' error, so
I checked the source. The source says 'return list(self.data)', and the
docstring clearly states 'Return a list of weak references to the keys'. I
think the docs should say the same. Should I raise an issue for this?
Frank Millman
More information about the Python-list
mailing list