Enumerating Classes in Modules

Jeff Shannon jeff at ccvcorp.com
Thu Nov 18 02:20:54 CET 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]):
        except AttributeError:

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
Credit International

More information about the Python-list mailing list