List classes in directory (Python)

Option 1: grep for "^class (\a\w+)\(Myclass" regexp with -r parameter.

Option 2: make the directory a package (create an empty __init__.py file), import it and iterate recursively over its members:

import mymodule
def itermodule(mod):
    for member in dir(mymod):
        ...

itermodule(mymodule)

I wanted to do the same thing, this is what I ended up with:

import glob
import importlib
import inspect
import os

current_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)))
current_module_name = os.path.splitext(os.path.basename(current_dir))[0]
for file in glob.glob(current_dir + "/*.py"):
     name = os.path.splitext(os.path.basename(file))[0]

     # Ignore __ files
     if name.startswith("__"):
         continue
     module = importlib.import_module("." + name,package=current_module_name)

     for member in dir(module):
         handler_class = getattr(module, member)

         if handler_class and inspect.isclass(handler_class):
             print member

Hope it helps..


Modules are never loaded automatically, but it should be easy to iterate over the modules in the directory and load them with the __import__ builtin function:

import os
from glob import glob
for file in glob(os.path.join(os.path.dirname(os.path.abspath(__file__))), "*.py"):
    name = os.path.splitext(os.path.basename(file))[0]
    # add package prefix to name, if required
    module = __import__(name)
    for member in dir(module):
        # do something with the member named ``member``