Mark import names as needing to be re-written.

        The named module or package as well as any nested modules will
        be re-written on import.
969176
def mark_rewrite(self, *names):
        
        already_imported = set(names).intersection(set(sys.modules))
        if already_imported:
            for name in already_imported:
                if name not in self._rewritten_names:
                    self._warn_already_imported(name)
        self._must_rewrite.update(names)
686298
def _import_packages(packages, optional=None):
    
    if not optional:
        optional = []

    package_references = set()

    # Check all reqiured packages
    failures = set()
    for package_name in packages:
        try:
            package_reference = __import__(package_name, globals(), locals(), [], 0)
            package_references.add(package_reference)
        except ImportError:
            failures.add(package_name)

    # Report aggregated list of import failures (save a developer time when building a new frozen environment)
    if failures:
        raise ImportError(u"Unable to find required packages: {0}".format(u", ".join(failures)))

    # Check all optional packages (and warn if some aren't found)
    failures = set()
    for package_name in optional:
        try:
            package_reference = __import__(package_name, globals(), locals(), [], 0)
            package_references.add(package_reference)
        except ImportError:
            failures.add(package_name)

    # Warn user which optional packages weren't found
    for failure in failures:
        warn(ImportWarning(u"Unable to import {0}".format(failure)))

    return package_references
496328
def my_import(name):
    
    mod = __import__(name)
    components = name.split('.')
    for comp in components[1:]:
        mod = getattr(mod, comp)
    return mod
335729
def rewrite_file_imports(item, vendored_libs):
    """"""
    text = item.read_text(encoding='utf-8')
    for lib in vendored_libs:
        text = re.sub(
            r'(\n\s*)import %s(\n\s*)' % lib,
            r'\1from pythonfinder._vendor import %s\2' % lib,
            text,
        )
        text = re.sub(
            r'(\n\s*)from %s' % lib,
            r'\1from pythonfinder._vendor.%s' % lib,
            text,
        )
    item.write_text(text, encoding='utf-8')
17795
def __push_import_modules(self):
        
        for module in self.__import_modules:
            sys.modules[module.__name__] = module
6076
def my_import(name, path=None):
    """"""

    # Documentation for importlib says this may be needed to pick up
    # modules created after the program has started
    if hasattr(importlib, 'invalidate_caches'):
        # python 3.3+
        importlib.invalidate_caches()

    if path is not None:
        directory, src_file = os.path.split(path)

        # TODO: use the importlib.util machinery
        sys.path.insert(0, directory)
        try:
            mod = importlib.import_module(name)
        finally:
            sys.path.pop(0)

    else:
        mod = importlib.import_module(name)

    return mod
495532
def add_module(  # noqa: C901
        self,
        module,
        module_or_package_name,
        local_names,
        import_alias_mapping,
        is_init=False,
        from_from=False,
        from_fdid=False
    ):
        
        module_path = module[1]

        parent_definitions = self.module_definitions_stack[-1]
        # Here, in `visit_Import` and in `visit_ImportFrom` are the only places the `import_alias_mapping` is updated
        parent_definitions.import_alias_mapping.update(import_alias_mapping)
        parent_definitions.import_names = local_names

        new_module_definitions = ModuleDefinitions(local_names, module_or_package_name)
        new_module_definitions.is_init = is_init
        self.module_definitions_stack.append(new_module_definitions)

        # Analyse the file
        self.filenames.append(module_path)
        self.local_modules = get_directory_modules(module_path) if self._allow_local_modules else []
        tree = generate_ast(module_path)

        # module[0] is None during e.g. "from . import foo", so we must str()
        self.nodes.append(EntryOrExitNode('Module Entry ' + str(module[0])))
        self.visit(tree)
        exit_node = self.append_node(EntryOrExitNode('Module Exit ' + str(module[0])))

        # Done analysing, pop the module off
        self.module_definitions_stack.pop()
        self.filenames.pop()

        if new_module_definitions.is_init:
            for def_ in new_module_definitions.definitions:
                module_def_alias = handle_aliases_in_init_files(
                    def_.name,
                    new_module_definitions.import_alias_mapping
                )
                parent_def_alias = handle_aliases_in_init_files(
                    def_.name,
                    parent_definitions.import_alias_mapping
                )
                # They should never both be set
                assert not (module_def_alias and parent_def_alias)

                def_name = def_.name
                if parent_def_alias:
                    def_name = parent_def_alias
                if module_def_alias:
                    def_name = module_def_alias

                local_definitions = self.module_definitions_stack[-1]
                if local_definitions != parent_definitions:
                    raise
                if not isinstance(module_or_package_name, str):
                    module_or_package_name = module_or_package_name.name

                if module_or_package_name:
                    if from_from:
                        qualified_name = def_name

                        if from_fdid:
                            alias = handle_fdid_aliases(module_or_package_name, import_alias_mapping)
                            if alias:
                                module_or_package_name = alias
                            parent_definition = ModuleDefinition(
                                parent_definitions,
                                qualified_name,
                                module_or_package_name,
                                self.filenames[-1]
                            )
                        else:
                            parent_definition = ModuleDefinition(
                                parent_definitions,
                                qualified_name,
                                None,
                                self.filenames[-1]
                            )
                    else:
                        qualified_name = module_or_package_name + '.' + def_name
                        parent_definition = ModuleDefinition(
                            parent_definitions,
                            qualified_name,
                            parent_definitions.module_name,
                            self.filenames[-1]
                        )
                    parent_definition.node = def_.node
                    parent_definitions.definitions.append(parent_definition)
                else:
                    parent_definition = ModuleDefinition(
                        parent_definitions,
                        def_name,
                        parent_definitions.module_name,
                        self.filenames[-1]
                    )
                    parent_definition.node = def_.node
                    parent_definitions.definitions.append(parent_definition)

        return exit_node
138133
def include(module_name, *module_names):
    
    def decorated(fn):
        _add_decorator(fn, "include", nargs=[module_name] + list(module_names))
        return fn

    return decorated
566594
def visit_Import(self, node):
        
        for alias in node.names:
            alias_name = tuple(alias.name.split('.'))
            self.imports.add(alias_name[0])
            if alias.asname:
                self.symbols[alias.asname] = alias_name
            else:
                self.symbols[alias_name[0]] = alias_name[:1]
            self.update = True
        return None
1235920
def do_import_module(self, modname=None):
        
        # handle special case where we are on a package node importing a module
        # using the same name as the package, which may end in an infinite loop
        # on relative imports
        # XXX: no more needed ?
        mymodule = self.root()
        level = getattr(self, "level", None)  # Import as no level
        if modname is None:
            modname = self.modname
        # XXX we should investigate deeper if we really want to check
        # importing itself: modname and mymodule.name be relative or absolute
        if mymodule.relative_to_absolute_name(modname, level) == mymodule.name:
            # FIXME: we used to raise InferenceError here, but why ?
            return mymodule

        return mymodule.import_module(
            modname, level=level, relative_only=level and level >= 1
        )
1301211
def _copy_module(old):
    """"""
    saved = sys.modules.pop(old.__name__, None)
    new = __import__(old.__name__)
    sys.modules[old.__name__] = saved
    return new
1189378
def _From(self, t):
        
        # fixme: Are From and ImportFrom handled differently?
        self._fill("from ")
        self._write(t.modname)
        self._write(" import ")
        for i, (name,asname) in enumerate(t.names):
            if i != 0:
                self._write(", ")
            self._write(name)
            if asname is not None:
                self._write(" as "+asname)
1037032
protected function reportModuleNamePrefixing()
    {
        foreach ($this->data->rawData['modules'] as $moduleId => $module) {
            if ( ! array_get($module, 'prefixed_name')) continue;

            $this->context->log(
                "Prefixed or altered module name to avoid duplicates: #{$moduleId} ("
                . "{$module['name']}) is now known as {$module['prefixed_name']}",
                Generator::LOG_LEVEL_WARNING
            );
        }
    }
823559
def visit_ImportFrom(self, node):
        """"""
        line = self._code_lines[node.lineno - 1]
        module_name = line.split("from")[1].split("import")[0].strip()
        for name in node.names:
            imported_name = name.name
            if name.asname:
                imported_name = name.asname + "::" + imported_name
            self.imported_names[imported_name] = module_name
146406
def namedModule(name):
    """"""
    topLevel = __import__(name)
    packages = name.split(".")[1:]
    m = topLevel
    for p in packages:
        m = getattr(m, p)
    return m
796679
def __recursive_import(module_name):
    
    names = module_name.split(".")
    path = None
    module = None
    while len(names) > 0:
        if module:
            path = module.__path__
        name = names.pop(0)
        (module_file, pathname, description) = imp.find_module(name, path)
        module = imp.load_module(name, module_file, pathname, description)
    return module
946800
def reload_module(module):
    
    try:
        # For Python 2.x
        reload(module)
    except (ImportError, NameError):
        # For <= Python3.3:
        import imp
        imp.reload(module)
    except (ImportError, NameError):
        # For >= Python3.4
        import importlib
        importlib.reload(module)