Return a list of ``(name, module)`` tuples

        This function tries to find modules that have a global name
        that starts with `starting`.
171247
def import_assist(self, starting):
        
        # XXX: breaking if gave up! use generators
        result = []
        for module in self.names:
            for global_name in self.names[module]:
                if global_name.startswith(starting):
                    result.append((global_name, module))
        return result
640129
def _import_all_modules():
    """"""
    import traceback
    import os
    global results
    globals_, locals_ = globals(), locals()

    def load_module(modulename, package_module):
        try:
            names = []
            module = __import__(package_module, globals_, locals_, [modulename])

            for name in module.__dict__:
                if not name.startswith('_'):
                    globals_[name] = module.__dict__[name]
                    names.append(name)
        except Exception:
            traceback.print_exc()
            raise

        return module, names

    def load_dir(abs_dirpath, rel_dirpath=''):
        results = []

        # dynamically import all the package modules
        for filename in os.listdir(abs_dirpath):
            rel_filepath = os.path.join(rel_dirpath, filename)
            abs_filepath = os.path.join(abs_dirpath, filename)

            if filename[0] != '_' and os.path.isfile(abs_filepath) and filename.split('.')[-1] in ('py', 'pyw'):
                modulename = '.'.join(os.path.normpath(os.path.splitext(rel_filepath)[0]).split(os.sep))
                package_module = '.'.join([__name__, modulename])

                module, names = load_module(modulename, package_module)
                results += names
            elif os.path.isdir(abs_filepath):
                results += load_dir(abs_filepath, rel_filepath)

        return results

    return load_dir(os.path.dirname(__file__))
1109437
def find_classes_in_module(module, clstypes):
    
    classes = []
    for item in dir(module):
        item = getattr(module, item)
        try:
            for cls in clstypes:
                if issubclass(item, cls) and item != cls:
                    classes.append(item)
        except Exception as e:
            pass
    return classes
465799
def _find_module(name, path=None):
    

    parts = name.split('.')

    for part in parts:
        if path is not None:
            path = [path]

        fh, path, descr = imp.find_module(part, path)
        if fh is not None and part != parts[-1]:
            fh.close()

    return fh, path, descr
695293
def _get_modules(path):
    
    lst = []
    folder_contents = os.listdir(path)
    is_python_module = "__init__.py" in folder_contents

    if is_python_module:
        for file in folder_contents:
            full_path = os.path.join(path, file)

            if is_file(full_path):
                lst.append(full_path)

            if is_folder(full_path):
                lst += _get_modules(full_path)  # recurse in folder

    return list(set(lst))
826450
def get_module_owned_functions(module):
    
    import utool as ut
    list_ = []
    for key, val in ut.iter_module_doctestable(module):
        belongs = False
        if hasattr(val, '__module__'):
            belongs = val.__module__ == module.__name__
        elif hasattr(val, 'func_globals'):
            belongs = val.func_globals['__name__'] == module.__name__
        if belongs:
            list_.append(val)
    return list_
601248
def _find_global(self, module, func):
        """"""
        if module == __name__:
            if func == '_unpickle_call_error' or func == 'CallError':
                return _unpickle_call_error
            elif func == '_unpickle_sender':
                return self._unpickle_sender
            elif func == '_unpickle_context':
                return self._unpickle_context
            elif func == 'Blob':
                return Blob
            elif func == 'Secret':
                return Secret
            elif func == 'Kwargs':
                return Kwargs
        elif module == '_codecs' and func == 'encode':
            return self._unpickle_bytes
        elif module == '__builtin__' and func == 'bytes':
            return BytesType
        raise StreamError('cannot unpickle %r/%r', module, func)
797955
def discover() -> List[Tuple[str, str]]:
    
    if IS_ROBOT and os.path.isdir('/dev/modules'):
        devices = os.listdir('/dev/modules')
    else:
        devices = []

    discovered_modules = []

    module_port_regex = re.compile('|'.join(MODULE_TYPES.keys()), re.I)
    for port in devices:
        match = module_port_regex.search(port)
        if match:
            name = match.group().lower()
            if name not in MODULE_TYPES:
                log.warning("Unexpected module connected: {} on {}"
                            .format(name, port))
                continue
            absolute_port = '/dev/modules/{}'.format(port)
            discovered_modules.append((absolute_port, name))
    log.info('Discovered modules: {}'.format(discovered_modules))

    return discovered_modules
515166
def get_modules(path, prepend_module_root=True):
    
    module_root = os.path.split(path)[1]
    modules = list()
    for root, directories, filenames in os.walk(path):
        for filename in filenames:
            if _is_python_file(filename):
                directory = os.path.dirname(
                    os.path.realpath(
                        os.path.join(
                            root,
                            filename
                        )
                    )
                ).split(module_root)[-1].replace(
                    os.sep,  # e.g. '/'
                    '.'
                )
                directory = directory.replace('.', '', 1)

                module_name_parts = []
                if prepend_module_root:
                    module_name_parts.append(module_root)
                if directory:
                    module_name_parts.append(directory)

                if filename == '__init__.py':
                    path = root
                else:
                    module_name_parts.append(os.path.splitext(filename)[0])
                    path = os.path.join(root, filename)

                modules.append(('.'.join(module_name_parts), path))

    return modules
742698
def get_app_submodules(module_name):
    
    for name, module in get_app_modules():
        if module_has_submodule(module, module_name):
            yield name, import_module('{0}.{1}'.format(name, module_name))
1075513
def get_imported_modules(cells, nb_module_name=''):
    ""
    module_names = get_top_level_modules()
    nb_imports = [match.group(1) for cell in cells for match in IMPORT_RE.finditer(cell['source']) if cell['cell_type'] == 'code']
    parts = nb_module_name.split('.')
    parent_modules = ['.'.join(parts[:(x+1)]) for x in range_of(parts)] # Imports parent modules - a.b.c = [a, a.b, a.b.c]
    all_modules = module_names + nb_imports + parent_modules
    mods = [import_mod(m, ignore_errors=True) for m in all_modules]
    return [m for m in mods if m is not None]
1189405
def globals(self):
        """"""
        try:
            return vars(__import__(self.module, fromlist=self.module.split('.')))
        except ImportError:
            if self.warn_import:
                warnings.warn(ImportWarning(
                    'Cannot import module {} for SerializableFunction. Restricting to builtins.'.format(self.module)
                ))
            return {'__builtins__': __builtins__}
380823
def _get_globals():
    """"""
    if _get_globals_callback is not None:
        return _get_globals_callback()
    else:
        try:
            from __main__ import __dict__ as namespace
        except ImportError:
            try:
                # The import fails on IronPython
                import __main__
                namespace = __main__.__dict__
            except:
                namespace
        shell = namespace.get('__ipythonshell__')
        if shell is not None and hasattr(shell, 'user_ns'):
            # IPython 0.12+ kernel
            return shell.user_ns
        else:
            # Python interpreter
            return namespace
        return namespace
649604
def listModules(self):
        """"""
        modules = list(self.modules.items())
        modules.sort()
        return [module for name, module in modules]
443311
def _get_starting_paths(self, curdir):
        

        results = [curdir]

        if not self._is_parent(curdir) and not self._is_this(curdir):
            fullpath = os.path.abspath(curdir)
            basename = os.path.basename(fullpath)
            dirname = os.path.dirname(fullpath)
            if basename:
                matcher = self._get_matcher(basename)
                results = [os.path.basename(name) for name in self._glob_dir(dirname, matcher, self)]

        return results
22389
def find_global(self, name):
        """"""
        defglobal = lib.EnvFindDefglobal(self._env, name.encode())
        if defglobal == ffi.NULL:
            raise LookupError("Global '%s' not found" % name)

        return Global(self._env, defglobal)
174613
def find_missing_modules():
    
    missing_modules = []

    for module in MODULES:
        try:
            __import__(module[1])
        except ImportError:
            missing_modules.append(module)
    return missing_modules