def get_subclasses(class_type, directory=None):
"""
Creates a dictionary of classes which inherit from ``class_type`` found in
all python files within a given directory, keyed by the class name in snake
case as a string.
:param class_type: The base class that all returned classes should inherit
from.
:type class_type: cls
:param directory: The directory to look for classes in.
:type directory: str
:returns: A dict of classes found.
:rtype: dict
"""
try:
glob_expression = os.path.join(directory, "*.py")
except (AttributeError, TypeError):
raise TypeError("'directory' object should be a string")
module_paths = glob.glob(glob_expression)
sys.path.append(directory)
modules = [
imp.load_source(
os.path.basename(module_path).split(".")[0], module_path
)
for module_path in module_paths
if "__init__" not in module_path
]
classes = {}
for module in modules:
for attr in module.__dict__.values():
if inspect.isclass(attr) \
and issubclass(attr, class_type) \
and not inspect.isabstract(attr):
classes[camel_to_snake_case(attr.__name__)] = attr
return classes
评论列表
文章目录