unloading imported modules

Alex Martelli aleax at aleax.it
Sun Jul 21 02:58:59 EDT 2002


On Sunday 21 July 2002 00:33, François Pinard wrote:
> [Alex Martelli]
>
> > > > > Is it possible in python intepreter to unload imported modules?
> > > >
> > > > No.
> >
> > 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).
>
> So, when the reference count of a module drops to 0, and I get that this
> is possible, then the module is unloaded.  Isn't it?  Also, I wonder if

Sure should be.  To double check, add prints in moduleobject.c, function
module_dealloc, rebuild Python and give it a try.

> a module coming from an `.so' file be effectively reloaded.  And then, if

Sure, why not?  

>>> import _socket
>>> _socket.ssl
<built-in function ssl>
>>> _socket.ssl=23
>>> _socket.ssl
23
>>> reload(_socket)
<module '_socket' from '/usr/local/lib/python2.2/lib-dynload/_socket.so'>
>>> _socket.ssl
<built-in function ssl>

See -- _socket.ssl is put back to the value at module load time,
because we used reload, even though we had bound it to something
else in the meantine.  Or what do you mean by "effectively reloaded"?

> the previous copy (the memory area in which the `.so' is paged) gets
> freed?

I would expect that to be platform-dependent, specifically
dependent on what dlclose does on the platform.  But, how
hard can it be to give it a try on the platform of your interest?


Alex





More information about the Python-list mailing list