Import modules from the given list of strings. Args: imports (list | str | None): The given module names to be imported. allow_failed_imports (bool): If True, the failed imports will return None. Otherwise, an ImportError is raise. Default: False. Returns:
(imports, allow_failed_imports=False)
| 36 | |
| 37 | |
| 38 | def import_modules_from_strings(imports, allow_failed_imports=False): |
| 39 | """Import modules from the given list of strings. |
| 40 | Args: |
| 41 | imports (list | str | None): The given module names to be imported. |
| 42 | allow_failed_imports (bool): If True, the failed imports will return |
| 43 | None. Otherwise, an ImportError is raise. Default: False. |
| 44 | Returns: |
| 45 | list[module] | module | None: The imported modules. |
| 46 | Examples: |
| 47 | >>> osp, sys = import_modules_from_strings( |
| 48 | ... ['os.path', 'sys']) |
| 49 | >>> import os.path as osp_ |
| 50 | >>> import sys as sys_ |
| 51 | >>> assert osp == osp_ |
| 52 | >>> assert sys == sys_ |
| 53 | """ |
| 54 | if not imports: |
| 55 | return |
| 56 | single_import = False |
| 57 | if isinstance(imports, str): |
| 58 | single_import = True |
| 59 | imports = [imports] |
| 60 | if not isinstance(imports, list): |
| 61 | raise TypeError( |
| 62 | f'custom_imports must be a list but got type {type(imports)}') |
| 63 | imported = [] |
| 64 | for imp in imports: |
| 65 | if not isinstance(imp, str): |
| 66 | raise TypeError( |
| 67 | f'{imp} is of type {type(imp)} and cannot be imported.') |
| 68 | try: |
| 69 | imported_tmp = import_module(imp) |
| 70 | except ImportError: |
| 71 | if allow_failed_imports: |
| 72 | warnings.warn(f'{imp} failed to import and is ignored.', |
| 73 | UserWarning) |
| 74 | imported_tmp = None |
| 75 | else: |
| 76 | raise ImportError |
| 77 | imported.append(imported_tmp) |
| 78 | if single_import: |
| 79 | imported = imported[0] |
| 80 | return imported |
| 81 | |
| 82 | |
| 83 | def iter_cast(inputs, dst_type, return_type=None): |
nothing calls this directly
no outgoing calls
no test coverage detected