In Python: How to remove an object from a list if it is only referenced in that list? : <p>I want to keep track of objects of a certain type that are currently in use. For example: Keep track of all instances of a class or all classes that have been created by a metaclass.</p>

<p>It is easy to keep track of instances like this:</p>

<pre><code>class A():
    instances = []
    def __init__(self):
        self.instances.append(self)
</code></pre>

<p>But if an instance is not referenced anywhere outside of that list it will not be needed anymore and I do not want to process that instance in a potentially time consuming loop.</p>

<p>I tried to remove objects that are only referenced in the list using sys.getrefcount.</p>

<pre><code>for i in A.instances:
    if sys.getrefcount(i) &lt;=3: # in the list, in the loop and in getrefcount
        # collect and remove after the loop
</code></pre>

<p>The problem I have is that the reference count is very obscure.
Opening a new shell and creating a dummy class with no content returns 5 for</p>

<pre><code>sys.getrefcount(DummyClass)
</code></pre>

<p>Another idea is to copy the objects then deleting the list and checking which objects have been scheduled for garbage collecting and in the last step removing those objects. Something like:</p>

<pre><code>Copy = copy(A.instances)
del A.instances
A.instances = [i for i in Copy if not copy_of_i_is_in_GC(i)]
</code></pre>

<p>The objects don't have to be removed immediately when the reference count goes to 0. I just don't want to waste too much ressources on objects that are not used anymore.</p>
