25 __all__ = (
"doImport",)
29 """Import a python object given an importable string and return it.
34 String containing dot-separated path of a Python class, module,
40 Type object. Either a module or class or a function.
45 ``importable`` is not a `str`.
47 No module in the supplied import string could be found.
49 ``importable`` is found but can not be imported or the requested
50 item could not be retrieved from the imported module.
52 if not isinstance(importable, str):
53 raise TypeError(f
"Unhandled type of importable, val: {importable}")
55 def tryImport(module, fromlist):
56 pytype = importlib.import_module(module)
60 pytype = getattr(pytype, f)
61 except AttributeError:
62 raise ImportError(f
"Could not get attribute '{f}' from '{module}'")
68 moduleComponents = importable.split(
".")
71 while moduleComponents:
73 pytype = tryImport(
".".join(moduleComponents), infileComponents)
74 if not infileComponents
and hasattr(pytype, moduleComponents[-1]):
80 return tryImport(
".".join(moduleComponents[:-1]), moduleComponents[-1:])
81 except ModuleNotFoundError:
84 except ModuleNotFoundError:
86 infileComponents.insert(0, moduleComponents.pop())
88 raise ModuleNotFoundError(f
"Unable to import {importable}")