Created
May 30, 2018 08:22
-
-
Save monkut/51d228b1d2c1b7a3e3e367df52534bc1 to your computer and use it in GitHub Desktop.
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
VALID_PYTHON_EXTENSIONS = ('.py', ) | |
def get_userdefined_class(directory: str, target_baseclass: object) -> list: | |
""" | |
Load Classes that sub-classed the given 'target_baseclass' for modules in the given directory | |
:param directory: directory containing user-defined classes subclassing 'target_baseclass' | |
:param target_baseclass: the ABC class that the user class subclasses | |
:return: (class) [UserDefinedClass, ...] | |
""" | |
import inspect | |
import importlib | |
# find classes subclassed from target_baseclass | |
userdefined_classes = [] | |
python_module_filepaths = [os.path.join(directory, f) for f in os.listdir(directory) if f.endswith(VALID_PYTHON_EXTENSIONS)] | |
for python_module_filepath in python_module_filepaths: | |
module_name, module_ext = os.path.splitext(os.path.basename(python_module_filepath)) | |
spec = importlib.util.spec_from_file_location(module_name, python_module_filepath) | |
module = importlib.util.module_from_spec(spec) | |
spec.loader.exec_module(module) | |
module_classes = inspect.getmembers(module, inspect.isclass) | |
for identifier, klass in module_classes: | |
if klass is not target_baseclass and issubclass(klass, target_baseclass): | |
userdefined_classes.append(klass) | |
return userdefined_classes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment