|
| 1 | +import importlib |
| 2 | + |
| 3 | + |
| 4 | +class AutoDiscover: |
| 5 | + """ |
| 6 | + This class search modules in this package recursively. What it does |
| 7 | + is actually search all the modules and run an `import_module` for each. |
| 8 | +
|
| 9 | + :param path: `pathlib.Path` object |
| 10 | + :param pattern: Must be a string for search likes string.endswith(pattern) |
| 11 | + :return: modules list |
| 12 | +
|
| 13 | + How to use: |
| 14 | +
|
| 15 | + autodiscover = Autodiscover(path=...) |
| 16 | + autodiscover() |
| 17 | + """ |
| 18 | + |
| 19 | + def __init__(self, path, pattern=None): |
| 20 | + self.path = path |
| 21 | + self.pattern = pattern |
| 22 | + self.root = '.'.join( |
| 23 | + reversed(self.__get_parts_until_root_recursively(path=path)) |
| 24 | + ) |
| 25 | + |
| 26 | + def __call__(self): |
| 27 | + return self.__autodiscover(path=self.path, pattern=self.pattern) |
| 28 | + |
| 29 | + def __get_parts_until_root_recursively(self, path): |
| 30 | + parts = [] |
| 31 | + try: |
| 32 | + next(path.glob('__init__.py')) |
| 33 | + except StopIteration: |
| 34 | + return parts |
| 35 | + parts.append(path.name) |
| 36 | + parts.extend(self.__get_parts_until_root_recursively(path.parent)) |
| 37 | + return parts |
| 38 | + |
| 39 | + def __autodiscover(self, path, pattern): |
| 40 | + modules = [] |
| 41 | + |
| 42 | + for obj in path.iterdir(): |
| 43 | + if obj.name.startswith('_'): |
| 44 | + continue |
| 45 | + |
| 46 | + if ( |
| 47 | + obj.is_file() |
| 48 | + and obj.suffix == '.py' |
| 49 | + and obj.match(pattern or '*') |
| 50 | + ): |
| 51 | + module_name = self.__normalize_module_name( |
| 52 | + module_name='.'.join(obj.parts).replace('.py', '') |
| 53 | + ) |
| 54 | + modules.append(importlib.import_module(module_name)) |
| 55 | + |
| 56 | + if obj.is_dir(): |
| 57 | + modules.extend(self.__autodiscover(path=obj, pattern=pattern)) |
| 58 | + |
| 59 | + return modules |
| 60 | + |
| 61 | + def __normalize_module_name(self, module_name): |
| 62 | + return module_name[module_name.find(self.root):] |
0 commit comments