Last active
July 10, 2017 05:39
-
-
Save ayemos/e1b366e3a222224450c9ed7f653e437d to your computer and use it in GitHub Desktop.
module以下にあってbase_classを継承しているクラスを列挙
This file contains 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
import inspect | |
import importlib | |
def list_classes(module, base_class): | |
return _list_classes(module, base_class, set()) | |
def _list_classes(module, base_class, result): | |
for maybe_class in [member[1] for member in inspect.getmembers(module)]: | |
if maybe_class is not None and inspect.isclass(maybe_class) and issubclass(maybe_class, base_class): | |
result.add(maybe_class) | |
for sig in module.__all__: | |
mod_or_class = '.'.join([module.__name__, sig]) | |
try: | |
mod = importlib.import_module(mod_or_class) | |
result |= _list_classes(mod, base_class, result) | |
except Exception as e: | |
continue | |
return result | |
if __name__ == '__main__': | |
import sklearn | |
from sklearn.base import ClassifierMixin | |
print('\n'.join([str(c) for c in list_classes(sklearn, ClassifierMixin)])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment