How can I explicitly free memory in Python?

How can I explicitly free memory in Python?

According to Python Official Documentation, you can explicitly invoke the Garbage Collector to release unreferenced memory with gc.collect(). Example:

import gc


You should do that after marking what you want to discard using del:

del my_array
del my_object

Unfortunately (depending on your version and release of Python) some types of objects use free lists which are a neat local optimization but may cause memory fragmentation, specifically by making more and more memory earmarked for only objects of a certain type and thereby unavailable to the general fund.

The only really reliable way to ensure that a large but temporary use of memory DOES return all resources to the system when its done, is to have that use happen in a subprocess, which does the memory-hungry work then terminates. Under such conditions, the operating system WILL do its job, and gladly recycle all the resources the subprocess may have gobbled up. Fortunately, the multiprocessing module makes this kind of operation (which used to be rather a pain) not too bad in modern versions of Python.

In your use case, it seems that the best way for the subprocesses to accumulate some results and yet ensure those results are available to the main process is to use semi-temporary files (by semi-temporary I mean, NOT the kind of files that automatically go away when closed, just ordinary files that you explicitly delete when youre all done with them).

How can I explicitly free memory in Python?

The del statement might be of use, but IIRC it isnt guaranteed to free the memory. The docs are here … and a why it isnt released is here.

I have heard people on Linux and Unix-type systems forking a python process to do some work, getting results and then killing it.

This article has notes on the Python garbage collector, but I think lack of memory control is the downside to managed memory

Leave a Reply

Your email address will not be published. Required fields are marked *