Enumerating Classes in Modules
Jeff Shannon
jeff at ccvcorp.com
Wed Nov 17 20:20:54 EST 2004
Rob Snyder wrote:
>Greetings -
>
>I have a situation where I need to be able to have a Python function that
>will take all the modules in a given directory and find all the classes
>defined in these modules by name. Ultimately, I would need to loop through
>all of these, instantiating each of the classes in turn and calling a
>pre-known method of each.
>
>Finding the name of each module is not a problem, but loading the classes
>out the module once I know the name is where I'm lost.
>
>
Hm. Any reason to not simply import the module (using the __import__()
function), going through all names in that module's namespace, and
attempting to call the method on them? (Catching AttributeErrors as
necessary, of course.)
Something like this (untested, unresearched, and totally off the top of
my head):
for modname in nameslist:
plugins[modname] = __import__(modname)
# ....
for item in dir(plugins[modname]):
try:
item.standard_method()
except AttributeError:
pass
If you need something a bit more specific, maybe you could require all
plugin classes to be derived from a common subclass, and before calling
the standard_method() you could check issubclass(item, plugin_base)...
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list