質問

I have a list of objects that I am iterating through.

After each loop, I want to set that object equal to None and force the garbage collector to run.

However I don't know how to assign the object instead of the element. For example:

a = [ object1, object2, object3]

for i in xrange(0,len(a)]:
       #do something with object
        ....
       #done working on object
       a[i] = None <-- This sets element i to None and leaves the object intact.

The reason I am trying this is because I am using a machine learning library and iterating through many classifiers. The classifiers keep in memory a large amount of predictions. Thus once I've written the predictions into a CSV, I no longer need them. That's why at the end of each loop, I'm hoping to delete the classifier and then run gc.collect() and ideally improve memory management.

So the question is, how do I assign the object to None?

役に立ちましたか?

解決

As commented by @thefourtheye:

When you assign None and no other references exist, the objects will be automatically marked for GC. You don't have to explicitly trigger that.

You are reducing the reference count of the actual object by assigning None to the list index. When you say a[i] = None you decrease the reference count of the object at a[i] by 1. If it had reference count 1, then it makes it to 0, and since nothing no longer references that object, it will be ready for GC.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top