Edit: here is a revised solution. I realized that I was making a mistake when testing my previous one, and this really is not the way you expected. So here is a more complete solution:
import os from imp import find_module from types import ModuleType, ClassType def iter_plugins(package): """Receives package (as a string) and, for all of its contained modules, generates all classes that are subclasses of PluginBaseClass."""
My previous solution was:
You can try something like:
from types import ModuleType import Plugins classes = [] for item in dir(Plugins): module = getattr(Plugins, item) # Get all (and only) modules in Plugins if type(module) == ModuleType: for c in dir(module): klass = getattr(module, c) if isinstance(klass, PluginBaseClass): classes.append(klass)
Actually, even better if you want modularity:
from types import ModuleType def iter_plugins(package): # This assumes "package" is a package name. # If it the package itself, you can remove this __import__ pkg = __import__(package) for item in dir(pkg): module = getattr(pkg, item) if type(module) == ModuleType: for c in dir(module): klass = getattr(module, c) if issubclass(klass, PluginBaseClass): yield klass
rbp
source share