How to unload a module after I've imported it.

J

Johny

Is it possible to unload a module after I've imported it.
I have the main program from which I import several smaller programs.
Some of these uses timeoutsocket module.
But one of the smaller program can not work with the timeoutsocket
module, so I must
unload the timeoutsocket module, execute the program and then reload
timeoutsocket module.
So, s it possible to unload a module after I've imported it..
Thanks
L.
 
G

Gabriel Genellina

Have you tried a del?
import socket
dir() ['__builtins__', '__doc__', '__name__', 'socket']
del socket
dir()
['__builtins__', '__doc__', '__name__']

py> import socket
py> del socket
py> import sys
py> sys.modules['socket']
<module 'socket' from 'c:\apps\Python25\lib\socket.pyc'>

del only removes the reference from the current namespace, but the module
is still loaded and available.
del sys.modules['socket'] would remove the module so the next import
statement will have to reload it.

Back to the original question, timeoutsocket replaces some objects in the
socket module with its own versions, just "unloading" timeoutsocket would
not be enough, the changes had to be reverted.

timeoutsocket is an old hack for Python 2.2 and earlier. Since 2.3 you can
achieve the same thing using socket.setdefaulttimeout() so unless you are
forced to use such ancient versions, it can be dropped.
 
F

Fuzzyman

Have you tried a del?

['__builtins__', '__doc__', '__name__', 'socket']>> del socket
['__builtins__', '__doc__', '__name__']

See you!
import socket
import sys
'socket' in sys.modules True
del sys.modules['socket']
'socket' in sys.modules
False

Although as Gabriel says, this may not be the best approach for this
particular need.

A new import will do a full reload of the socket module.

Michael
http://www.manning.com/foord
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top