Ejemplo n.º 1
0
    def ast_from_module_name(self, modname, context_file=None):
        """given a module name, return the astroid object"""
        if modname in self.astroid_cache:
            return self.astroid_cache[modname]
        if modname == "__main__":
            return self._build_stub_module(modname)
        old_cwd = os.getcwd()
        if context_file:
            os.chdir(os.path.dirname(context_file))
        try:
            found_spec = self.file_from_module_name(modname, context_file)
            if found_spec.type == spec.ModuleType.PY_ZIPMODULE:
                module = self.zip_import_data(found_spec.location)
                if module is not None:
                    return module

            elif found_spec.type in (
                    spec.ModuleType.C_BUILTIN,
                    spec.ModuleType.C_EXTENSION,
            ):
                if (found_spec.type == spec.ModuleType.C_EXTENSION
                        and not self._can_load_extension(modname)):
                    return self._build_stub_module(modname)
                try:
                    module = modutils.load_module_from_name(modname)
                except Exception as ex:
                    raise exceptions.AstroidImportError(
                        "Loading {modname} failed with:\n{error}",
                        modname=modname,
                        path=found_spec.location,
                    ) from ex
                return self.ast_from_module(module, modname)

            elif found_spec.type == spec.ModuleType.PY_COMPILED:
                raise exceptions.AstroidImportError(
                    "Unable to load compiled module {modname}.",
                    modname=modname,
                    path=found_spec.location,
                )

            elif found_spec.type == spec.ModuleType.PY_NAMESPACE:
                return self._build_namespace_module(
                    modname, found_spec.submodule_search_locations)

            if found_spec.location is None:
                raise exceptions.AstroidImportError(
                    "Can't find a file for module {modname}.", modname=modname)

            return self.ast_from_file(found_spec.location,
                                      modname,
                                      fallback=False)
        except exceptions.AstroidBuildingError as e:
            for hook in self._failed_import_hooks:
                try:
                    return hook(modname)
                except exceptions.AstroidBuildingError:
                    pass
            raise e
        finally:
            os.chdir(old_cwd)
Ejemplo n.º 2
0
 def infer_ast_from_something(self, obj, context=None):
     """infer astroid for the given class"""
     if hasattr(obj, '__class__') and not isinstance(obj, type):
         klass = obj.__class__
     else:
         klass = obj
     try:
         modname = klass.__module__
     except AttributeError as exc:
         raise exceptions.AstroidBuildingError(
             'Unable to get module for {class_repr}.',
             cls=klass, class_repr=safe_repr(klass)) from exc
     except Exception as exc:
         raise exceptions.AstroidImportError(
             'Unexpected error while retrieving module for {class_repr}:\n'
             '{error}', cls=klass, class_repr=safe_repr(klass)) from exc
     try:
         name = klass.__name__
     except AttributeError as exc:
         raise exceptions.AstroidBuildingError(
             'Unable to get name for {class_repr}:\n',
             cls=klass, class_repr=safe_repr(klass)) from exc
     except Exception as exc:
         raise exceptions.AstroidImportError(
             'Unexpected error while retrieving name for {class_repr}:\n'
             '{error}', cls=klass, class_repr=safe_repr(klass)) from exc
     # take care, on living object __module__ is regularly wrong :(
     modastroid = self.ast_from_module_name(modname)
     if klass is obj:
         for inferred in modastroid.igetattr(name, context):
             yield inferred
     else:
         for inferred in modastroid.igetattr(name, context):
             yield inferred.instantiate_class()
Ejemplo n.º 3
0
 def ast_from_module_name(self, modname, context_file=None):
     """given a module name, return the astroid object"""
     if modname in self.astroid_cache:
         return self.astroid_cache[modname]
     if modname == '__main__':
         return self._build_stub_module(modname)
     old_cwd = os.getcwd()
     if context_file:
         os.chdir(os.path.dirname(context_file))
     try:
         filepath, mp_type = self.file_from_module_name(
             modname, context_file)
         if mp_type == modutils.PY_ZIPMODULE:
             module = self.zip_import_data(filepath)
             if module is not None:
                 return module
         elif mp_type in (imp.C_BUILTIN, imp.C_EXTENSION):
             if mp_type == imp.C_EXTENSION and not self._can_load_extension(
                     modname):
                 return self._build_stub_module(modname)
             try:
                 module = modutils.load_module_from_name(modname)
             except Exception as ex:  # pylint: disable=broad-except
                 util.reraise(
                     exceptions.AstroidImportError(
                         'Loading {modname} failed with:\n{error}',
                         modname=modname,
                         path=filepath,
                         error=ex))
             return self.ast_from_module(module, modname)
         elif mp_type == imp.PY_COMPILED:
             raise exceptions.AstroidImportError(
                 "Unable to load compiled module {modname}.",
                 modname=modname,
                 path=filepath)
         if filepath is None:
             raise exceptions.AstroidImportError(
                 "Can't find a file for module {modname}.", modname=modname)
         return self.ast_from_file(filepath, modname, fallback=False)
     except exceptions.AstroidBuildingError as e:
         for hook in self._failed_import_hooks:
             try:
                 return hook(modname)
             except exceptions.AstroidBuildingError:
                 pass
         raise e
     finally:
         os.chdir(old_cwd)
Ejemplo n.º 4
0
 def file_from_module_name(self, modname, contextfile):
     try:
         value = self._mod_file_cache[(modname, contextfile)]
     except KeyError:
         try:
             value = modutils.file_info_from_modpath(
                 modname.split('.'), context_file=contextfile)
         except ImportError as ex:
             value = exceptions.AstroidImportError(
                 'Failed to import module {modname} with error:\n{error}.',
                 modname=modname, error=ex)
         self._mod_file_cache[(modname, contextfile)] = value
     if isinstance(value, exceptions.AstroidBuildingError):
         raise value
     return value
Ejemplo n.º 5
0
 def file_from_module_name(self, modname, contextfile):
     try:
         value = self._mod_file_cache[(modname, contextfile)]
     except KeyError:
         try:
             value = modutils.file_info_from_modpath(
                 modname.split("."), context_file=contextfile)
         except ImportError as ex:
             value = exceptions.AstroidImportError(
                 "Failed to import module {modname} with error:\n{error}.",
                 modname=modname,
                 # we remove the traceback here to save on memory usage (since these exceptions are cached)
                 error=ex.with_traceback(None),
             )
         self._mod_file_cache[(modname, contextfile)] = value
     if isinstance(value, exceptions.AstroidBuildingError):
         # we remove the traceback here to save on memory usage (since these exceptions are cached)
         raise value.with_traceback(None)
     return value
Ejemplo n.º 6
0
    def ast_from_module_name(self, modname, context_file=None):
        """given a module name, return the astroid object"""
        if modname in self.astroid_cache:
            return self.astroid_cache[modname]
        if modname == '__main__':
            return self._build_stub_module(modname)
        old_cwd = os.getcwd()
        if context_file:
            os.chdir(os.path.dirname(context_file))
        try:
            found_spec = self.file_from_module_name(modname, context_file)
            # pylint: disable=no-member
            if found_spec.type == spec.ModuleType.PY_ZIPMODULE:
                # pylint: disable=no-member
                module = self.zip_import_data(found_spec.location)
                if module is not None:
                    return module

            elif found_spec.type in (spec.ModuleType.C_BUILTIN,
                                     spec.ModuleType.C_EXTENSION):
                # pylint: disable=no-member
                if (found_spec.type == spec.ModuleType.C_EXTENSION
                        and not self._can_load_extension(modname)):
                    return self._build_stub_module(modname)
                try:
                    module = modutils.load_module_from_name(modname)
                except Exception as ex:  # pylint: disable=broad-except
                    util.reraise(
                        exceptions.AstroidImportError(
                            'Loading {modname} failed with:\n{error}',
                            modname=modname,
                            path=spec.location,
                            error=ex))
                return self.ast_from_module(module, modname)

            elif found_spec.type == spec.ModuleType.PY_COMPILED:
                raise exceptions.AstroidImportError(
                    "Unable to load compiled module {modname}.",
                    # pylint: disable=no-member
                    modname=modname,
                    path=found_spec.location)

            elif found_spec.type == spec.ModuleType.PY_NAMESPACE:
                return self._build_namespace_module(
                    modname,
                    # pylint: disable=no-member
                    found_spec.submodule_search_locations)

            # pylint: disable=no-member
            if found_spec.location is None:
                raise exceptions.AstroidImportError(
                    "Can't find a file for module {modname}.", modname=modname)

            # pylint: disable=no-member
            return self.ast_from_file(found_spec.location,
                                      modname,
                                      fallback=False)
        except exceptions.AstroidBuildingError as e:
            for hook in self._failed_import_hooks:
                try:
                    return hook(modname)
                except exceptions.AstroidBuildingError:
                    pass
            # pylint: disable=raising-bad-type; https://github.com/PyCQA/pylint/issues/157
            raise e
        finally:
            os.chdir(old_cwd)