Reputation: 978
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)?
Upvotes: 2
Views: 121
Reputation: 304315
In addition to what @nneonneo said, you should periodically scan through your list of cursor weak references and cull out the None
s otherwise you will end up with an ever growing list of None
s
Upvotes: 4
Reputation: 179482
Use a weak reference from the weakref
module 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
.
>>> import weakref
>>> class Cursor: pass
...
>>> _ = None # suppress special _ variable
>>> a = Cursor()
>>> r = weakref.ref(a)
>>> print r()
<__main__.Cursor instance at 0x1004a2bd8>
>>> del a
>>> print r()
None
You can put all those weakrefs in a collection (or use WeakKeyDictionary
, WeakValueDictionary
, or WeakSet
) to keep track of the various cursors you have to update.
Upvotes: 6