简体   繁体   English

Python:如何跟踪对象是否仍处于“使用”状态?

[英]Python: How do I keep track of whether an object is still in 'use'?

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). 游标由两部分列表[start, end] ,每次插入/删除文本时都需要更新(开始/结束索引向前或向后移动)。

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.) (例如:它有一个关于'bob'一词的所有搜索结果的游标列表,并且对'fred'这个词进行了新的搜索,所以现在用一个新的游标列表替换它的结果列表。 。旧列表及其游标不再使用。)

I can require that any object using the cursor calls a .finished() method when it no longer needs it. 我可以要求使用游标的任何对象在不再需要时调用.finished()方法。 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)? 我如何在python中检查这个(我知道垃圾清理维护一个列表,并在不再引用时删除它)?

Use a weak reference from the weakref module to hold your cursor reference. 使用weakref模块中的弱引用来保存光标引用。

When the referent of a weak reference no longer has any strong (normal) references to it, the weakref will resolve to None . 当弱引用的引用不再具有对它的任何强(正常)引用时,weakref将解析为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. 您可以将所有这些weakref放在集合中(或使用WeakKeyDictionaryWeakValueDictionaryWeakSet )来跟踪您必须更新的各种游标。

除了@nneonneo所说的,你应该定期浏览你的光标弱引用列表并剔除None s否则你将会得到一个不断增长的None列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM