Tries to determine if a module is a python std import, third party import, or project code:

        if it can't determine - it assumes it is project code
434807
def place_module(self, module_name):
        
        for forced_separate in self.config['forced_separate']:
            # Ensure all forced_separate patterns will match to end of string
            path_glob = forced_separate
            if not forced_separate.endswith('*'):
                path_glob = '%s*' % forced_separate

            if fnmatch(module_name, path_glob) or fnmatch(module_name, '.' + path_glob):
                return forced_separate

        if module_name.startswith("."):
            return self.sections.LOCALFOLDER

        # Try to find most specific placement instruction match (if any)
        parts = module_name.split('.')
        module_names_to_check = ['.'.join(parts[:first_k]) for first_k in range(len(parts), 0, -1)]
        for module_name_to_check in module_names_to_check:
            for pattern, placement in self.known_patterns:
                if pattern.match(module_name_to_check):
                    return placement

        # Use a copy of sys.path to avoid any unintended modifications
        # to it - e.g. `+=` used below will change paths in place and
        # if not copied, consequently sys.path, which will grow unbounded
        # with duplicates on every call to this method.
        paths = list(sys.path)
        virtual_env = self.config.get('virtual_env') or os.environ.get('VIRTUAL_ENV')
        virtual_env_src = False
        if virtual_env:
            paths += [path for path in glob('{0}/lib/python*/site-packages'.format(virtual_env))
                      if path not in paths]
            paths += [path for path in glob('{0}/src/*'.format(virtual_env)) if os.path.isdir(path)]
            virtual_env_src = '{0}/src/'.format(virtual_env)

        # handle case-insensitive paths on windows
        stdlib_lib_prefix = os.path.normcase(get_stdlib_path())

        for prefix in paths:
            module_path = "/".join((prefix, module_name.replace(".", "/")))
            package_path = "/".join((prefix, module_name.split(".")[0]))
            is_module = (exists_case_sensitive(module_path + ".py") or
                         exists_case_sensitive(module_path + ".so"))
            is_package = exists_case_sensitive(package_path) and os.path.isdir(package_path)
            if is_module or is_package:
                if ('site-packages' in prefix or 'dist-packages' in prefix or
                        (virtual_env and virtual_env_src in prefix)):
                    return self.sections.THIRDPARTY
                elif os.path.normcase(prefix).startswith(stdlib_lib_prefix):
                    return self.sections.STDLIB
                else:
                    return self.config['default_section']

        return self.config['default_section']
1258213
def _check_import_source():
        """"""
        path_rel = '~/cltk_data/greek/software/greek_software_tlgu/tlgu.h'
        path = os.path.expanduser(path_rel)
        if not os.path.isfile(path):
            try:
                corpus_importer = CorpusImporter('greek')
                corpus_importer.import_corpus('greek_software_tlgu')
            except Exception as exc:
                logger.error('Failed to import TLGU: %s', exc)
                raise
1037270
def _try_import(module_name):
  """"""
  try:
    mod = importlib.import_module(module_name)
    return mod
  except ImportError:
    err_msg = ("Tried importing %s but failed. See setup.py extras_require. "
               "The dataset you are trying to use may have additional "
               "dependencies.")
    utils.reraise(err_msg)
12122
def imported_from_bootstrap(self, module):
    

    # A vendored module.
    path = getattr(module, '__file__', None)
    if path and os.path.realpath(path).startswith(self._realpath):
      return True

    # A vendored package.
    path = getattr(module, '__path__', None)
    if path and any(os.path.realpath(path_item).startswith(self._realpath)
                    for path_item in path):
      return True

    return False
1153106
def get_inst_type(xml_node: XmlNode):
    ''''''
    (module_path, class_name) = (xml_node.namespace, xml_node.name)
    try:
        return import_module(module_path).__dict__[class_name]
    except (KeyError, ImportError, ModuleNotFoundError):
        message = 'Import "{0}.{1}" is failed.'.format(module_path, class_name)
        raise RenderingError(message, xml_node.view_info)
248244
def stdlib(self):
        
        if self.module == 'pkg_resources' or self.module.startswith('pkg_resources.'):
            return False
        elif self.filename.startswith(SITE_PACKAGES_PATHS):
            # if it's in site-packages then its definitely not stdlib
            return False
        elif self.filename.startswith(SYS_PREFIX_PATHS):
            return True
        else:
            return False
860904
def _collect_from_package(self, module,
                              type_checker: Optional[FunctionType] = None,
                              ) -> Dict[str, Any]:
        
        type_checker = type_checker or self.type_check
        members = dict(self._get_members(module, type_checker))

        if pkgutil.get_loader(module).is_package(module.__name__):
            for loader, name, is_pkg in pkgutil.walk_packages(module.__path__):
                child_module_name = f'{module.__package__}.{name}'
                child_module = importlib.import_module(child_module_name)
                for key, obj in self._get_members(child_module, type_checker):
                    if key not in members:
                        members[key] = obj

        return members
261841
def is_stdlib_name(modname):
    
    if imp.is_builtin(modname) != 0:
        return True

    module = sys.modules.get(modname)
    if module is None:
        return False

    # six installs crap with no __file__
    modpath = os.path.abspath(getattr(module, '__file__', ''))
    return is_stdlib_path(modpath)
1326512
def is_py_script(filename):
    ""
    if not os.path.exists(filename) and os.path.isfile(filename):
        return False
    elif filename.endswith(".py"):
        return True
    elif not os.access(filename, os.X_OK):
        return False
    else:
        try:
            with open(filename, "r") as fp:
                first_line = fp.readline().strip()
            return "#!" in first_line and "python" in first_line
        except StopIteration:
            return False
952910
def is_builtin_module(module_name):
    """"""
    module_name = module_name.split(".")[0]
    return (module_name in MODULES or
            (module_name in cxx_keywords and module_name + "_" in MODULES))
87803
def isdefined(obj, force_import=False, namespace=None):
    """"""
    if namespace is None:
        namespace = locals()
    attr_list = obj.split('.')
    base = attr_list.pop(0)
    if len(base) == 0:
        return False
    if base not in builtins.__dict__ and base not in namespace:
        if force_import:
            try:
                module = __import__(base, globals(), namespace)
                if base not in globals():
                    globals()[base] = module
                namespace[base] = module
            except Exception:
                return False
        else:
            return False
    for attr in attr_list:
        try:
            attr_not_found = not hasattr(eval(base, namespace), attr)
        except (SyntaxError, AttributeError):
            return False
        if attr_not_found:
            if force_import:
                try:
                    __import__(base+'.'+attr, globals(), namespace)
                except (ImportError, SyntaxError):
                    return False
            else:
                return False
        base += '.'+attr
    return True
340906
def is_cython(obj):
    """"""

    # TODO(suo): We could split these into two functions, one for Cython
    # functions and another for Cython methods.
    # TODO(suo): There doesn't appear to be a Cython function 'type' we can
    # check against via isinstance. Please correct me if I'm wrong.
    def check_cython(x):
        return type(x).__name__ == "cython_function_or_method"

    # Check if function or method, respectively
    return check_cython(obj) or \
        (hasattr(obj, "__func__") and check_cython(obj.__func__))
1335231
def is_class_or_module(self):
        

        if isinstance(self.obj, ObjectDouble):
            return self.obj.is_class

        return isclass(self.doubled_obj) or ismodule(self.doubled_obj)
29544
def python_script_exists(package=None, module=None):
    
    assert module is not None
    try:
        if package is None:
            path = imp.find_module(module)[1]
        else:
            path = osp.join(imp.find_module(package)[1], module)+'.py'
    except ImportError:
        return
    if not osp.isfile(path):
        path += 'w'
    if osp.isfile(path):
        return path
820790
def check_imported(module):
        
        imported = True
        module_info = ('', '', '')
        # TODO: if possible, update to a cleaner method that doesn't require importing the module
        # and running inline code.
        try:
            importlib.import_module(module)
            module_info = imp.find_module(module)
        except ImportError:
            imported = False

        # get module path
        module_path = module_info[1]
        description = module_info[2]

        if not description:
            # if description is None or empty string the module could not be imported
            imported = False
        elif not description and not module_path:
            # if description/module_path are None or empty string the module could not be imported
            imported = False
        elif module_path is not None and (
            'dist-packages' in module_path or 'site-packages' in module_path
        ):
            # if dist-packages|site-packages in module_path the import doesn't count
            imported = False
        return imported
87156
def _is_import_binding(node, name, package=None):
    

    if node.type == syms.import_name and not package:
        imp = node.children[1]
        if imp.type == syms.dotted_as_names:
            for child in imp.children:
                if child.type == syms.dotted_as_name:
                    if child.children[2].value == name:
                        return node
                elif child.type == token.NAME and child.value == name:
                    return node
        elif imp.type == syms.dotted_as_name:
            last = imp.children[-1]
            if last.type == token.NAME and last.value == name:
                return node
        elif imp.type == token.NAME and imp.value == name:
            return node
    elif node.type == syms.import_from:
        # unicode(...) is used to make life easier here, because
        # from a.b import parses to ['import', ['a', '.', 'b'], ...]
        if package and unicode(node.children[1]).strip() != package:
            return None
        n = node.children[3]
        if package and _find(u"as", n):
            # See test_from_import_as for explanation
            return None
        elif n.type == syms.import_as_names and _find(name, n):
            return node
        elif n.type == syms.import_as_name:
            child = n.children[2]
            if child.type == token.NAME and child.value == name:
                return node
        elif n.type == token.NAME and n.value == name:
            return node
        elif package and n.type == token.STAR:
            return node
    return None
642882
def resolve_import(name, is_from, is_star):
    
    # Don't try to resolve relative imports or builtins here; they will be
    # handled by resolve.Resolver
    if name.startswith('.') or is_builtin(name):
        return None
    ret = _resolve_import(name)
    if ret is None and is_from and not is_star:
        package, _ = name.rsplit('.', 1)
        ret = _resolve_import(package)
    return ret