Import all submodules of a module, recursively
    Adapted from: http://stackoverflow.com/a/25083161

    :param package_name: Package name
    :type package_name: str
    :rtype: dict[types.ModuleType]
767123
def _import_submodules(package_name):
    
    package = sys.modules[package_name]
    out = {}
    for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
        try:
            #module = importlib.import_module('{}.{}'.format(package_name, name))
            module = importlib.import_module('.{}'.format(name), package=package_name)
            out[name] = module
        except:
            continue
    return out
847325
def import_all_modules(package, skip=None, verbose=False, prefix="", depth=0):
    

    skip = [] if skip is None else skip

    for ff, modname, ispkg in pkgutil.walk_packages(path=package.__path__,
                                                prefix=prefix,
                                                onerror=lambda x: None):
        if ff.path not in package.__path__[0]: # Solves weird bug
            continue
        if verbose:
            print('\t'*depth,modname)
        if modname in skip:
            if verbose:
                print('\t'*depth,'*Skipping*')
            continue
        module = '%s.%s' % (package.__name__,modname)
        subpackage = importlib.import_module(module)
        if ispkg:
            import_all_modules(subpackage, skip=skip,
                               verbose=verbose,depth=depth+1)
1183074
def import_module(name: str) -> ModuleType:
    
    logger.debug("Importing module: %s", name)
    if name == main_module_name():
        return main_module

    return importlib.import_module(name)
1181853
def import_module(module_name):
    """"""
    import sys, os
    import importlib
    sys.path.append(os.path.dirname(__file__))
    return importlib.import_module(module_name)
444516
def load_plugins_from_module(module_name):
    
    plugins = {}

    try:
        if module_name.endswith('.py'):
            import imp
            mod = imp.load_source('module.name', module_name)
        else:
            mod = importlib.import_module(module_name)
    except Exception as e:
        logger.debug("Import module <{}> failed: {}".format(module_name, e))
        return {}
    for _, cls in inspect.getmembers(mod, inspect.isclass):
        # Don't try to register plugins imported into this module elsewhere
        if issubclass(cls, (Catalog, DataSource)):
            plugins[cls.name] = cls

    return plugins
1055920
def explore_package(module_name):
    

    packages = []
    loader = pkgutil.get_loader(module_name)
    for sub_module in pkgutil.walk_packages([os.path.dirname(loader.get_filename())],
                                            prefix=module_name + '.'):
        _, sub_module_name, _ = sub_module
        packages.append(sub_module_name)

    return packages
913118
def load_model_from_package(name, **overrides):
    """"""
    cls = importlib.import_module(name)
    return cls.load(**overrides)
1374305
def load_module(self, fullname):
        
        mod = sys.modules.setdefault(fullname, imp.new_module(fullname))
        mod.__file__ = self._path
        mod.__loader__ = self
        mod.__path__ = []
        mod.__package__ = fullname
        return mod
220183
def as_dict(self):
        
        return {
            'name': str(self),
            'modules': [m.as_dict() for m in self.modules],
            'packages': [p.as_dict() for p in self.packages]
        }
1110497
def load(self, *modules):
        
        for module in modules:
            if isinstance(module, six.string_types):
                try:
                    module = get_object(module)
                except Exception as e:
                    self.errors[module] = e
                    continue
            self.modules[module.__package__] = module
            for (loader, module_name, is_pkg) in pkgutil.walk_packages(
                module.__path__
            ):
                full_name = "{}.{}".format(_package(module), module_name)
                try:
                    self.modules[full_name] = get_object(full_name)
                    if is_pkg:
                        self.load(self.modules[full_name])
                except Exception as e:
                    self.errors[full_name] = e
851287
def import_submodules(package, recursive=True):
    
    if isinstance(package, str):
        package = importlib.import_module(package)
    results = {}
    for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
        full_name = package.__name__ + "." + name
        results[name] = importlib.import_module(full_name)
        if recursive and is_pkg:
            results.update(import_submodules(full_name))
    return results
1241945
def import_recursive(path):
    
    results = {}
    obj = importlib.import_module(path)
    results[path] = obj
    path = getattr(obj, '__path__', os.path.dirname(obj.__file__))
    for loader, name, is_pkg in pkgutil.walk_packages(path):
        full_name = obj.__name__ + '.' + name
        results[full_name] = importlib.import_module(full_name)
        if is_pkg:
            results.update(import_recursive(full_name))
    return results
967230
def _save_subimports(self, code, top_level_dependencies):
        
        # check if any known dependency is an imported package
        for x in top_level_dependencies:
            if isinstance(x, types.ModuleType) and hasattr(x, '__package__') and x.__package__:
                # check if the package has any currently loaded sub-imports
                prefix = x.__name__ + '.'
                for name, module in sys.modules.items():
                    # Older versions of pytest will add a "None" module to sys.modules.
                    if name is not None and name.startswith(prefix):
                        # check whether the function can address the sub-module
                        tokens = set(name[len(prefix):].split('.'))
                        if not tokens - set(code.co_names):
                            # ensure unpickler executes this import
                            self.save(module)
                            # then discards the reference to it
                            self.write(pickle.POP)
1003519
def import_related_module(package, pkg_path, related_name,
                          ignore_exceptions=False):
    """"""
    try:
        imp.find_module(related_name, pkg_path)
    except ImportError:
        return

    try:
        return getattr(
            __import__('%s' % (package), globals(), locals(), [related_name]),
            related_name
        )
    except Exception as e:
        if ignore_exceptions:
            current_app.logger.exception(
                'Can not import "{}" package'.format(package)
            )
        else:
            raise e
125277
def get_mod_subcmds(mod):
    

    ## Look in modules attributes

    subcmds = get_obj_subcmds(mod)

    path = os.path.dirname(os.path.realpath(mod.__file__))
    if mod.__package__ is None:
        sys.path.insert(0, os.path.dirname(path))
        mod.__package__ = kf.basename(path)

    for module_name in get_module_resources(mod):
        try:
            mod = importlib.import_module(".%s" % module_name, mod.__package__)
        except ImportError as e:
            msg.warn("%r could not be loaded: %s"
                     % (module_name, e.message))
            continue
        except IOError as e:
            print("%s" % module_name)
            raise
        if hasattr(mod, "Command") and is_cmd(mod.Command):
            obj = mod.Command
            if obj.__doc__ is None:
                msg.warn("Missing doc string for command from "
                         "module %s" % module_name)
                continue
            if isinstance(obj, type):
                obj = obj()  ## instanciate it.
            name = module_name.split("_", 1)[1]
            if name in subcmds:
                raise ValueError(
                    "Module command %r conflicts with already defined object "
                    "command."
                    % name)
            subcmds[name] = obj

    return subcmds
623655
def import_submodules(package_name: str) -> None:
    
    importlib.invalidate_caches()

    # For some reason, python doesn't always add this by default to your path, but you pretty much
    # always want it when using `--include-package`.  And if it's already there, adding it again at
    # the end won't hurt anything.
    sys.path.append('.')

    # Import at top level
    module = importlib.import_module(package_name)
    path = getattr(module, '__path__', [])
    path_string = '' if not path else path[0]

    # walk_packages only finds immediate children, so need to recurse.
    for module_finder, name, _ in pkgutil.walk_packages(path):
        # Sometimes when you import third-party libraries that are on your path,
        # `pkgutil.walk_packages` returns those too, so we need to skip them.
        if path_string and module_finder.path != path_string:
            continue
        subpackage = f"{package_name}.{name}"
        import_submodules(subpackage)
1292134
def _iter_module_subclasses(package, module_name, base_cls):
    
    module = importlib.import_module('.' + module_name, package)
    for name, obj in inspect.getmembers(module):
        if inspect.isclass(obj) and issubclass(obj, base_cls):
            yield obj