Created
May 31, 2018 03:40
-
-
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'
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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