Question: I am in the process of coding an app which has to get the metadata (author,version..etc) out of several modules (.py files) and display them. The user selects a script and the script is executed. (New scripts can be added and old ones be taken of from the target folder just like a plugin system).

Firstly I import a script and I take out the metadata, then I go for the next.
But I want to de-import all the other modules except for the one that the user has selected.

How can I implement this?

I tried these

```
1. del module
2. del sys.modules['module']

```

The latter did not work. I tried #python and got the answer that it was not good to de-import modules, but I want to know a clean way of implementing this. Any ideas/suggestions would help.

Answer: 
Suggestion: Import your modules dynamically using `__import__`

E.g.

```
module_list = ['os', 'decimal', 'random']
for module in module_list:
    x = __import__(module)
    print 'name: %s - module_obj: %s' % (x.__name__, x)

```

Will produce:

```
name: os - module_obj: <module 'os' from '/usr/lib64/python2.4/os.pyc'>
name: decimal - module_obj: <module 'decimal' from '/usr/lib64/python2.4/decimal.pyc'>
name: random - module_obj: <module 'random' from '/usr/lib64/python2.4/random.pyc'>

```

Though, this won't really remove it from the modules registry. The next time that it is imported, it won't re-read the package/module file and it won't execute it. To accomplish that, you can simply modify the above code snippet like this:

```
import sys
module_list = ['os', 'decimal', 'random', 'test1']
for module_name in module_list:
    x = __import__(module_name)
    print 'name: %s - module_obj: %s' % (x.__name__, x)
    del x
    sys.modules.pop(module_name)

```
I know this post has been out of date but I just encountered this issue and was struggling against it for the past few days. Now I came with a conclusion that can perfectly solve this issue. Please see the sample code below:

```
try:
    theMod = sys.modules['ModNeedToBeDel']   
except:
    theMod = None
if theMod:
    del sys.modules['ModNeedToBeDel']

#The extra try/except below is because I implemented the block in a module of a sub-package; this ModNeedToBeDel in my case was imported either by the toppest level Main code, or by the other sub-package modules. That's why I need two different try/except.

try:
    theMod = sys.modules['UpperFolder.ModNeedToBeDel']   
except:
    theMod = None
if theMod:
    del sys.modules['UpperFolder.ModNeedToBeDel']
import ModNeedToBeDel   # or UpperFolder.ModNeedToBeDel here

```

Note that `del sys.modules[theMod]` won't work, because it just deletes the reference, instead of the actual `ModNeedToBeDel`.

Hope this could help someone so that they won't have to struggle on this issue for several days!