howto load and unload a module
Peter Hansen
peter at engcorp.com
Fri Jun 24 09:09:32 EDT 2005
John Machin wrote:
> Peter Hansen wrote:
[sample code]
> Ummm ... doesn't appear to scale well for multiple modules and multiple
> attributes & functions.
It certainly wouldn't! :-) I was posting mainly to elicit more
information, since clearly you wouldn't get far hardcoding all the names
you were interested in. (It's hard to judge a poster's level of
expertise in Python without any example code from him. That makes it
too likely to go way above the head of the poster, and possibly provide
a much more complex solution than he really needs.)
> 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
Of course, one could simply hand the man a complete answer... ;-)
-Peter
More information about the Python-list
mailing list