(
folder: str, name_pattern: str, base_class: Type[T], one_per_file: bool = True
)
| 25 | |
| 26 | |
| 27 | def load_classes_from_folder( |
| 28 | folder: str, name_pattern: str, base_class: Type[T], one_per_file: bool = True |
| 29 | ) -> list[Type[T]]: |
| 30 | classes = [] |
| 31 | abs_folder = get_abs_path(folder) |
| 32 | |
| 33 | # Get all .py files in the folder that match the pattern, sorted alphabetically |
| 34 | py_files = sorted( |
| 35 | [ |
| 36 | file_name |
| 37 | for file_name in os.listdir(abs_folder) |
| 38 | if fnmatch(file_name, name_pattern) and file_name.endswith(".py") |
| 39 | ] |
| 40 | ) |
| 41 | |
| 42 | # Iterate through the sorted list of files |
| 43 | for file_name in py_files: |
| 44 | file_path = os.path.join(abs_folder, file_name) |
| 45 | # Use the new import_module function |
| 46 | module = import_module(file_path) |
| 47 | |
| 48 | # Get all classes in the module |
| 49 | class_list = inspect.getmembers(module, inspect.isclass) |
| 50 | |
| 51 | # Filter for classes that are subclasses of the given base_class |
| 52 | # iterate backwards to skip imported superclasses |
| 53 | for cls in reversed(class_list): |
| 54 | if cls[1] is not base_class and issubclass(cls[1], base_class): |
| 55 | classes.append(cls[1]) |
| 56 | if one_per_file: |
| 57 | break |
| 58 | |
| 59 | return classes |
| 60 | |
| 61 | |
| 62 | def load_classes_from_file( |
nothing calls this directly
no test coverage detected