howto load and unload a module

Peter Hansen peter at engcorp.com
Fri Jun 24 07:24:04 EDT 2005


Guy Robinson wrote:
> I have a directory of python scripts that all (should) contain a number 
> of attributes and methods of the same name.
> 
> I need to import each module, test for these items and unload the 
> module. I have 2 questions.
> 
> 1.. How do unload an imported module?

Why would you want to?  Doing what you describe doesn't require that you 
"unload" a module, unless that means something more to you than, say, 
merely releasing the memory used by it (which is likely insignificant to 
you).

> 2.. how do I test for the existance of a method in a module without 
> running it?

The object bound to the name used in the import statement is, well, an 
object, so you can use the usual tests:

import mymodule
try:
     mymodule.myfunction
except AttributeError:
     print 'myfunction does not exist'

or use getattr(), or some of the introspection features available in the 
"inspect" module.

-Peter



More information about the Python-list mailing list