Skip to content

Instantly share code, notes, and snippets.

@monkut
Created May 31, 2018 03:40
Show Gist options
  • Save monkut/c206321cb1e5a9c32c40589eee3cf7dd to your computer and use it in GitHub Desktop.
Save monkut/c206321cb1e5a9c32c40589eee3cf7dd to your computer and use it in GitHub Desktop.
Voodoo function to discover classes in given 'package' that subclass the given 'target_baseclass'
def _get_package_defined_classes(package, target_baseclass) -> dict:
"""
Voodoo function to discover classes in given 'package' that subclass the given 'target_baseclass'
:param package: Python Package Object
:param target_baseclass: Python Class Object
:return:
{
CLASS_NAME: CLASS_OBJECT,
...
}
"""
import inspect
import importlib
import pkgutil
defined_classes = {}
for importer, module_name, is_pkg in pkgutil.iter_modules(package.__path__, package.__name__ + '.'):
module = importlib.import_module(module_name)
module_classes = inspect.getmembers(module, inspect.isclass)
for identifier, klass in module_classes:
if klass is not target_baseclass and issubclass(klass, target_baseclass):
defined_classes[identifier] = klass
return defined_classes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment