MCPcopy Create free account
hub / github.com/10Ring/LAA-Net / import_modules_from_strings

Function import_modules_from_strings

register/misc.py:38–80  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

36
37
38def 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
83def iter_cast(inputs, dst_type, return_type=None):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected