Scan all the available classes and functions in the MONAI package and map them with the module paths in a table. It's used to locate the module path for provided component name. Args: excludes: if any string of the `excludes` exists in the full module name, don't import this mo
| 48 | |
| 49 | |
| 50 | class ComponentLocator: |
| 51 | """ |
| 52 | Scan all the available classes and functions in the MONAI package and map them with the module paths in a table. |
| 53 | It's used to locate the module path for provided component name. |
| 54 | |
| 55 | Args: |
| 56 | excludes: if any string of the `excludes` exists in the full module name, don't import this module. |
| 57 | |
| 58 | """ |
| 59 | |
| 60 | MOD_START = "monai" |
| 61 | |
| 62 | def __init__(self, excludes: Sequence[str] | str | None = None): |
| 63 | self.excludes = [] if excludes is None else ensure_tuple(excludes) |
| 64 | self._components_table: dict[str, list] | None = None |
| 65 | |
| 66 | def _find_module_names(self) -> list[str]: |
| 67 | """ |
| 68 | Find all the modules start with MOD_START and don't contain any of `excludes`. |
| 69 | |
| 70 | """ |
| 71 | return [m for m in sys.modules if m.startswith(self.MOD_START) and all(s not in m for s in self.excludes)] |
| 72 | |
| 73 | def _find_classes_or_functions(self, modnames: Sequence[str] | str) -> dict[str, list]: |
| 74 | """ |
| 75 | Find all the classes and functions in the modules with specified `modnames`. |
| 76 | |
| 77 | Args: |
| 78 | modnames: names of the target modules to find all the classes and functions. |
| 79 | |
| 80 | """ |
| 81 | table: dict[str, list] = {} |
| 82 | # all the MONAI modules are already loaded by `load_submodules` |
| 83 | for modname in ensure_tuple(modnames): |
| 84 | try: |
| 85 | # scan all the classes and functions in the module |
| 86 | module = import_module(modname) |
| 87 | for name, obj in inspect.getmembers(module): |
| 88 | if (inspect.isclass(obj) or inspect.isfunction(obj)) and obj.__module__ == modname: |
| 89 | if name not in table: |
| 90 | table[name] = [] |
| 91 | table[name].append(modname) |
| 92 | except ModuleNotFoundError: |
| 93 | pass |
| 94 | return table |
| 95 | |
| 96 | def get_component_module_name(self, name: str) -> list[str] | str | None: |
| 97 | """ |
| 98 | Get the full module name of the class or function with specified ``name``. |
| 99 | If target component name exists in multiple packages or modules, return a list of full module names. |
| 100 | |
| 101 | Args: |
| 102 | name: name of the expected class or function. |
| 103 | |
| 104 | """ |
| 105 | if not isinstance(name, str): |
| 106 | raise ValueError(f"`name` must be a valid string, but got: {name}.") |
| 107 | if self._components_table is None: |
no outgoing calls
searching dependent graphs…