How do I really delete an imported module?

Peter Otten __peter__ at web.de
Mon Dec 22 04:34:10 EST 2003


Jp Calderone wrote:

> On Sun, Dec 21, 2003 at 02:24:07PM +0000, William Trenker wrote:
>> I've been googling around trying to figure out how to delete an imported
>> module and free up the memory it was using.  One point of confusion, for
>> me, is that if I "del" a module the virtual memory used by the process
>> doesn't decrease.  Using Python 2.3.2 on Linux, here is a simple test

[...]

>   One important thing to realize is that "import re" does not just create
> one reference to the "re" module.  It also creates a reference at
> sys.modules['re'], and possibly in many other places as well.  Each of the
> modules listed in the output above also is referenced from sys.modules, so
> there is no possibility of them being garbage collected until that
> reference is removed.

You can use sys.getrefcount() to find out the actual number of references.

>>> import sys, empty, os
>>> sys.getrefcount(sys)
9
>>> sys.getrefcount(os)
6
>>> sys.getrefcount(empty)
3

Numbers greater than 3 indicate that it will be hard to get rid of the
module. The homegrown "empty" (containing nothing) module should be garbage
collected after

>>> del sys.modules["empty"]
>>> del empty

as the third reference is an artifact of the getrefcount() function.

>> What is the pythonic way to completely delete a module and get it's
>> memory garbage collected?

The pythonic way is probably not to bother :-)

Peter





More information about the Python-list mailing list