def import_injector(attr_list, namespace, package=None, quiet=False, fatal=False): """import list of modules and consume their __all__ attrs""" additional = [] for s in list(attr_list): try: m = import_module("." + s, package=package) namespace[s] = m # print(">", package, ">", s) # print(">", package, ">", s, "::", getattr(m, "__all__", None)) if hasattr(m, "__all__"): all_subattrs = getattr(m, "__all__") additional += all_subattrs for sub in all_subattrs: # print(" ", sub, "=", getattr(m, sub)) namespace[sub] = getattr(m, sub) except ImportError as e: if s not in namespace: _on_injected_import_error(s, e, quiet=quiet) attr_list.remove(s) if fatal: raise attr_list += additional
def _get_obj(rt, path): if len(path) == 0: return rt try: if not hasattr(rt, path[0]): try: # if path[0] is not an attribute of rt, then try # importing it module_name = "{0}.{1}".format(rt.__name__, path[0]) import_module(module_name) except ImportError: # nope, the attribute really doesn't exist raise AttributeError("root {0} has no attribute " "{1}".format(rt, path[0])) return _get_obj(getattr(rt, path[0]), path[1:]) except AttributeError: # can't re-raise AttributeError since this is recursive # and we're catching AttributeError, so the info about # what part of the path DNE would be lost raise RCPathError("'{0}' has no attribute '{1}'" "".format(rt.__name__, path[0]))