On 2018-10-16 11:10, Frank Millman wrote: > 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.
This sounds reasonable, though what you probably really want is a signal/slot library that does all of this for you, like PySignal. I believe all the pure-Python signal/slot libraries use weakrefs internally. -- Thomas -- https://mail.python.org/mailman/listinfo/python-list