newbie question - remove a module from ram

Peter Otten __peter__ at web.de
Mon May 10 12:09:44 EDT 2004


Paul McGuire wrote:

> "Peter Otten" <__peter__ at web.de> wrote in message
> news:c7nvr1$fsc$01$1 at news.t-online.com...
>> Paul McGuire wrote:
>>
>> > "john fabiani" <jfabiani at yolo.com> wrote in message
>> > news:4AAnc.6791$dH5.4946 at newssvr27.news.prodigy.com...
>> >> Hi,
>> >>
>> >> I believe I have good understanding of import but it occurred to me
> that
>> >> I might want to remove an imported module.  I.e I load a module into
> ram
>> >> and I no longer need the module.  Modules just stays in ram?  In the
>> >> windows world I would "thisform.release()"  and the garbage collector
>> >> would release the ram.  So did I miss something or is there no release
>> >> method.  How about a method within a class like destroy()?
>> >>
>> >> I just got to believe it's there????  But where?
>> >> John
>> >
>> > Well, you were pretty close with calling something like .release(). 
>> > Use the del statement.
>> >
>> >>>> import random
>> >>>> print random.random()
>> > 0.475899061786
>> >>>> del random
>> >>>> print random.random()
>> > Traceback (most recent call last):
>> >   File "<stdin>", line 1, in ?
>> > NameError: name 'random' is not defined
>> >>>>
>>
>> and then
>>
>> >>> import sys
>> >>> sys.modules["random"].random()
>> 0.43459738002826365
>> >>>
>>
>> should make it clear that (next to) no memory is freed in the process.
>>
>> Peter
>>
> So then what if he follows up with:
> 
>     del sys.modules["random"]
> 
> Are there any other dangling references to this module that would stymie
> the garbage collector (assuming that the OP hasn't saved off his own
> reference to the module)?

Python 2.3.3 (#1, Jan  3 2004, 13:57:08)
[GCC 3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import random, sys, weakref
>>> sys.getrefcount(random)
3
>>> del sys.modules["random"]
>>> sys.getrefcount(random)
2

This is one reference for the function call and one for the __main__.random
reference, i. e. reference count should indeed go to zero if we perform

del random

I could not trick the module into telling me directly:

>>> def f(r): print "i'm gone"
...
>>> w = weakref.ref(random, f)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: cannot create weak reference to 'module' object
>>>

Second try, working around the limitations of weak references:

>>> import random, sys, weakref
>>> class Flag: pass
...
>>> random.flag = Flag()
>>> def goodbye(r): print "I'm gone"
...
>>> w = weakref.ref(random.flag, goodbye)
>>> del random
>>> del sys.modules["random"]
I'm gone
>>>

So at least the objects in the module are garbage-collected. 

Peter




More information about the Python-list mailing list