Is there any way to remove an imported library?

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__'] (Currently imported packages)
>>> import time
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'time']
New module, "time". If you wanted to "un-import" a library, how would you do it?
Something like

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__'] (Currently imported packages)
>>> import time
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'time'] (New library time)
>>> un-import(time) (For an example command, anything like this?)
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__'] (Library "time" removed)

HTMLperson5
Deleted Member

It's not very useful. You could del time to remove the name time from the current namespace, but it would not unimport the module. The module is still in sys.modules['time']. You could del sys.modules[module.__name__], but it would not really unimport it as other modules may keep a reference to the module.

What you can try is reload(module). It runs the module's python code a second time. Unfortunately it doesn't reinitialize C modules like time because in C-python, such modules are shared libraries.

If you want to import a module only temporarily to perform a specific task, one way is to launch a python child process which imports the module (using module multiprocessing for example) instead of importing it directly in the main process.

Edited 4 Years Ago by Gribouillis

run

help('import')

My question, why would you want to remove an imported module?

Edited 4 Years Ago by HiHe

This article has been dead for over six months. Start a new discussion instead.