unloading imported modules

Alex Martelli aleax at aleax.it
Sat Jul 20 16:43:12 EDT 2002


On Saturday 20 July 2002 10:26 pm, François Pinard wrote:
> [Alex Martelli]
>
> > xeon wrote:
> > > Is it possible in python intepreter to unload imported modules? or are
> >
> > No.
>
> Hello, Alex.
>
> Suppose we reload, and reload and reload the same module, are the previous
> copies freed from memory?  If not, then, sigh, I guess, this is it...

When you reload(x), the module object x (another reference to which is in
sys.modules['x'], and possibly others yet in other modules) is altered so that
its contents is "just as if" you had just imported it.  There are no "copies":
there's only one module object involved.  Try -- id(x) is always one and the
same.  Any *attribute* of the module that may not be referenced any more
would have its reference count drop to 0 and be garbage-collected (at
once in classic Python, perhaps-later in Jython).

> Otherwise, if I remove the module from sys.modules and from the module
> namespace having imported it, what would keep it in memory?

References to the module are going to be in all modules that imported
it, plus one in sys.modules, plus any other reference you may have taken
e.g. via assignment statements.  Use sys.getrefcount(x) to know how
many references there are to object x, be it a module or any other kind
of object.  When the reference count of an object drops to 0, the object
is freed (at once, or eventually).  One way to keep something in memory
forever is to involve it in a reference loop with an instance of a class that
defines __del__ -- a good reason to avoid __del__ in most cases:-).

Built-in modules are different, of course -- e.g., no way you can get
rid of module sys, nohow:-).


Alex





More information about the Python-list mailing list