howto load and unload a module

John Machin sjmachin at lexicon.net
Fri Jun 24 09:03:17 EDT 2005


Peter Hansen wrote:
> 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.
[snip]
>> 2.. how do I test for the existance of a method in a module without 
>> running it?

What the OP is calling a 'method' is more usually called a 'function' 
when it is defined at module level rather than class level.

> 
> 
> 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.
> 

Ummm ... doesn't appear to scale well for multiple modules and multiple 
attributes & functions. Try something like this (mostly tested):

modules = ['foomod', 'barmod', 'brentstr', 'zotmod']
attrs = ['att1', 'att2', 'att3', 'MyString']
funcs = ['fun1', 'fun2', 'fun3']
# the above could even be read from file(s)
for modname in modules:
     try:
         mod = __import__(modname)
     except ImportError:
         print "module", modname, "not found"
         continue
     for attrname in attrs:
         try:
             attr = getattr(mod, attrname)
         except AttributeError:
             print "module %s has no attribute named %s" % \
                 (modname, attrname)
             continue
         # check that attr is NOT a function (maybe)
     for funcname in funcs:
         pass
         # similar to above but check that it IS a function


BTW, question for the OP: what on earth is the use-case for this? Bulk 
checking of scripts written by students?

Cheers,
John



More information about the Python-list mailing list