I have a text editing program that hands out cursors to other parts of the program that require it. The cursor consists of a two part list, [start, end], which needs to be updated every time text is inserted/removed (the start/end index gets moved forward or backwards).
When the cursor is no longer used, I want to stop updating it, since there are many and they are time consuming to update. By not in use, I mean that the object that requested it no longer references it – it no longer cares about it. (For example: it has a list of cursors to all search results for the word ‘bob’, and a new search was made for the word ‘fred’, so now it replaces its result list with a new list of new cursors… the old list and its cursors are no longer used.)
I can require that any object using the cursor calls a .finished() method when it no longer needs it. But it would be easier if I could detect when it is no longer being referenced by anything outside of the editor. How do I check this in python (I know the garbage cleanup maintains a list, and deletes it when no longer referenced)?
Use a weak reference from the
weakrefmodule to hold your cursor reference.When the referent of a weak reference no longer has any strong (normal) references to it, the weakref will resolve to
None.You can put all those weakrefs in a collection (or use
WeakKeyDictionary,WeakValueDictionary, orWeakSet) to keep track of the various cursors you have to update.