4
votes

I am using Python (Canopy) extensively for Earth science application. Because my application is memory consuming, I am trying find way to erase variable that I don't need any more in my programs, I tried to use del command to erase the variable memory, but I found that space used by Canopy is still the same. Any ideas about how to erase variable completely from the memory. thanks

1
Is there a test case you could show us? Also, try __import__("gc").collect(). - d33tah
When using a language like Python, you really don't have any direct control over when memory is deallocated. If you need that level of control, consider writing your code in C and handling memory management yourself. - larsks
Canopy uses an ipython kernel that may keep variables for future interactive use; depending on what you are doing, restarting the kernel is sometimes a good idea to restore memory and refresh the namespace. - Reblochon Masque
del does not delete objects, it removes references to them. Use sys.getrefcount() or weakrefs to see whether there's something that is keeping an object alive - Andrea Corbellini

1 Answers

5
votes

You can't manually nuke an object from your memory in Python!

The Python Garbage Collector (GC) will automatically free up memory of objects that have no existing references any more (implementation details differ per interpreter). It's periodically checking for abandoned objects in background without your interaction.

So to get an object recycled, you have to eliminate all references to it by assigning a different value (e.g. None) to all variables that pointed to the object. You can also delete a variable name using the del statement, but as you already noticed, this only deletes the name with the reference, but not the object and its data itself. Only the GC can do that.