1

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?

Terence Chow
  • 10,755
  • 24
  • 78
  • 141
  • 2
    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. – thefourtheye Apr 04 '14 at 01:58
  • @thefourtheye yes, but assigning `a[i] = None` sets element a[i] to None but object1 still exists. That's because I'm essentially assigning a list element and not the object. Also, this [question](http://stackoverflow.com/questions/1316767/how-can-i-explicitly-free-memory-in-python) has a comment that suggests running `gc.collect()` after each loop improves runtime by 20% so I want to try it out – Terence Chow Apr 04 '14 at 01:59
  • 2
    You are correct, but you are reducing the reference count of the actual object by assigning `None` to the list index. When you say `a[i] = None`, and if the object at `a[i]` had reference count `1`, then it makes it to 0, since `a[i]` no longer references that object. So, it will be ready for GC. – thefourtheye Apr 04 '14 at 02:02
  • 1
    @thefourtheye Ahhhhh that makes sense! Ok, do you want to add that as an answer and I will accept? – Terence Chow Apr 04 '14 at 02:03

1 Answers1

0

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.

dwitvliet
  • 7,242
  • 7
  • 36
  • 62