MCPcopy
hub / github.com/Vchitect/Latte / get_module_from_obj_name

Function get_module_from_obj_name

tools/dnnlib/util.py:225–263  ·  view source on GitHub ↗

Searches for the underlying module behind the name to some python object. Returns the module and the object name (original name with module part removed).

(obj_name: str)

Source from the content-addressed store, hash-verified

223# ------------------------------------------------------------------------------------------
224
225def get_module_from_obj_name(obj_name: str) -> Tuple[types.ModuleType, str]:
226 """Searches for the underlying module behind the name to some python object.
227 Returns the module and the object name (original name with module part removed)."""
228
229 # allow convenience shorthands, substitute them by full names
230 obj_name = re.sub("^np.", "numpy.", obj_name)
231 obj_name = re.sub("^tf.", "tensorflow.", obj_name)
232
233 # list alternatives for (module_name, local_obj_name)
234 parts = obj_name.split(".")
235 name_pairs = [(".".join(parts[:i]), ".".join(parts[i:])) for i in range(len(parts), 0, -1)]
236
237 # try each alternative in turn
238 for module_name, local_obj_name in name_pairs:
239 try:
240 module = importlib.import_module(module_name) # may raise ImportError
241 get_obj_from_module(module, local_obj_name) # may raise AttributeError
242 return module, local_obj_name
243 except:
244 pass
245
246 # maybe some of the modules themselves contain errors?
247 for module_name, _local_obj_name in name_pairs:
248 try:
249 importlib.import_module(module_name) # may raise ImportError
250 except ImportError:
251 if not str(sys.exc_info()[1]).startswith("No module named '" + module_name + "'"):
252 raise
253
254 # maybe the requested attribute is missing?
255 for module_name, local_obj_name in name_pairs:
256 try:
257 module = importlib.import_module(module_name) # may raise ImportError
258 get_obj_from_module(module, local_obj_name) # may raise AttributeError
259 except ImportError:
260 pass
261
262 # we are out of luck, but we have no idea why
263 raise ImportError(obj_name)
264
265
266def get_obj_from_module(module: types.ModuleType, obj_name: str) -> Any:

Callers 2

get_obj_by_nameFunction · 0.85

Calls 2

get_obj_from_moduleFunction · 0.85
subMethod · 0.80

Tested by

no test coverage detected