Example #1
0
def infer_import_from(self, context=None, asname=True):
    """infer a ImportFrom node: return the imported module/object"""
    name = context.lookupname
    if name is None:
        raise exceptions.InferenceError(node=self, context=context)
    if asname:
        name = self.real_name(name)

    try:
        module = self.do_import_module()
    except exceptions.AstroidBuildingError as exc:
        raise exceptions.InferenceError(
            node=self,
            context=context,
        ) from exc

    try:
        context = contextmod.copy_context(context)
        context.lookupname = name
        stmts = module.getattr(name, ignore_locals=module is self.root())
        return bases._infer_stmts(stmts, context)
    except exceptions.AttributeInferenceError as error:
        raise exceptions.InferenceError(
            error.message,
            target=self,
            attribute=name,
            context=context,
        ) from error
 def igetattr(self, name, context=None):
     """inferred getattr, need special treatment in class to handle
     descriptors
     """
     # set lookup name since this is necessary to infer on import nodes for
     # instance
     context = copy_context(context)
     context.lookupname = name
     try:
         for infered in _infer_stmts(self.getattr(name, context), context, frame=self):
             # yield YES object instead of descriptors when necessary
             if not isinstance(infered, Const) and isinstance(infered, Instance):
                 try:
                     infered._proxied.getattr("__get__", context)
                 except NotFoundError:
                     yield infered
                 else:
                     yield YES
             else:
                 yield function_to_method(infered, self)
     except NotFoundError:
         if not name.startswith("__") and self.has_dynamic_getattr(context):
             # class handle some dynamic attributes, return a YES object
             yield YES
         else:
             raise InferenceError(name)
Example #3
0
def infer_global(self, context=None, lookupname=None):
    if lookupname is None:
        raise InferenceError()
    try:
        return _infer_stmts(self.root().getattr(lookupname), context)
    except NotFoundError:
        raise InferenceError()
Example #4
0
def infer_name(self, context=None):
    """infer a Name: use name lookup rules"""
    frame, stmts = self.lookup(self.name)
    if not stmts:
        raise UnresolvableName(self.name)
    context = context.clone()
    context.lookupname = self.name
    return _infer_stmts(stmts, context, frame)
Example #5
0
def infer_global(self, context=None):
    if context.lookupname is None:
        raise exceptions.InferenceError()
    try:
        return bases._infer_stmts(self.root().getattr(context.lookupname),
                                  context)
    except exceptions.NotFoundError:
        raise exceptions.InferenceError()
Example #6
0
    def ilookup(self, name):
        """infered lookup

        return an iterator on infered values of the statements returned by
        the lookup method
        """
        frame, stmts = self.lookup(name)
        return _infer_stmts(stmts, None, frame)
Example #7
0
    def ilookup(self, name):
        """inferred lookup

        return an iterator on inferred values of the statements returned by
        the lookup method
        """
        frame, stmts = self.lookup(name)
        context = contextmod.InferenceContext()
        return bases._infer_stmts(stmts, context, frame)
Example #8
0
def infer_ass(self, context=None):
    """infer a AssName/AssAttr: need to inspect the RHS part of the
    assign node
    """
    stmt = self.statement()
    if isinstance(stmt, nodes.AugAssign):
        return stmt.infer(context)
    stmts = list(self.assigned_stmts(context=context))
    return _infer_stmts(stmts, context)
def infer_global(self, context=None):
    if context.lookupname is None:
        raise exceptions.InferenceError(node=self, context=context)
    try:
        return bases._infer_stmts(self.root().getattr(context.lookupname),
                                  context)
    except exceptions.AttributeInferenceError as error:
        util.reraise(exceptions.InferenceError(
            error.message, target=self, attribute=name, context=context))
Example #10
0
def infer_assign(self, context=None):
    """infer a AssignName/AssignAttr: need to inspect the RHS part of the
    assign node
    """
    stmt = self.statement()
    if isinstance(stmt, nodes.AugAssign):
        return stmt.infer(context)

    stmts = list(self.assigned_stmts(context=context))
    return bases._infer_stmts(stmts, context)
Example #11
0
def infer_global(self, context=None):
    if context.lookupname is None:
        raise exceptions.InferenceError(node=self, context=context)
    try:
        return bases._infer_stmts(self.root().getattr(context.lookupname),
                                  context)
    except exceptions.AttributeInferenceError as error:
        util.reraise(exceptions.InferenceError(
            error.message, target=self, attribute=context.lookupname,
            context=context))
Example #12
0
 def igetattr(self, name, context=None):
     """inferred getattr"""
     # set lookup name since this is necessary to infer on import nodes for
     # instance
     context = copy_context(context)
     context.lookupname = name
     try:
         return _infer_stmts(self.getattr(name, context), context, frame=self)
     except NotFoundError:
         raise InferenceError(name)
Example #13
0
 def igetattr(self, name, context=None):
     """inferred getattr"""
     # set lookup name since this is necessary to infer on import nodes for
     # instance
     context = copy_context(context)
     context.lookupname = name
     try:
         return _infer_stmts(self.getattr(name, context), context, frame=self)
     except NotFoundError:
         raise InferenceError(name)
Example #14
0
def infer_from(self, context=None, asname=True, lookupname=None):
    """infer a From nodes: return the imported module/object"""
    if lookupname is None:
        raise InferenceError()
    if asname:
        lookupname = self.real_name(lookupname)
    module = self.do_import_module()
    try:
        return _infer_stmts(module.getattr(lookupname, ignore_locals=module is self.root()), context, lookupname=lookupname)
    except NotFoundError:
        raise InferenceError(lookupname)
Example #15
0
def infer_global(self, context=None):
    if context.lookupname is None:
        raise InferenceError(node=self, context=context)
    try:
        return bases._infer_stmts(self.root().getattr(context.lookupname),
                                  context)
    except AttributeInferenceError as error:
        raise InferenceError(str(error),
                             target=self,
                             attribute=context.lookupname,
                             context=context) from error
Example #16
0
    def igetattr(self, name, context=None):
        """Retrieve the inferred values of the given attribute name."""

        if name in self.special_attributes:
            yield self.special_attributes.lookup(name)
            return

        try:
            mro = self.super_mro()
        # Don't let invalid MROs or invalid super calls
        # leak out as is from this function.
        except exceptions.SuperError as exc:
            raise exceptions.AttributeInferenceError(
                ('Lookup for {name} on {target!r} because super call {super!r} '
                 'is invalid.'),
                target=self, attribute=name, context=context, super_=exc.super_) from exc
        except exceptions.MroError as exc:
            raise exceptions.AttributeInferenceError(
                ('Lookup for {name} on {target!r} failed because {cls!r} has an '
                 'invalid MRO.'),
                target=self, attribute=name, context=context, mros=exc.mros,
                cls=exc.cls) from exc
        found = False
        for cls in mro:
            if name not in cls.locals:
                continue

            found = True
            for inferred in bases._infer_stmts([cls[name]], context, frame=self):
                if not isinstance(inferred, scoped_nodes.FunctionDef):
                    yield inferred
                    continue

                # We can obtain different descriptors from a super depending
                # on what we are accessing and where the super call is.
                if inferred.type == 'classmethod':
                    yield bases.BoundMethod(inferred, cls)
                elif self._scope.type == 'classmethod' and inferred.type == 'method':
                    yield inferred
                elif self._class_based or inferred.type == 'staticmethod':
                    yield inferred
                elif bases._is_property(inferred):
                    # TODO: support other descriptors as well.
                    try:
                        yield from inferred.infer_call_result(self, context)
                    except exceptions.InferenceError:
                        yield util.Uninferable
                else:
                    yield bases.BoundMethod(inferred, cls)

        if not found:
            raise exceptions.AttributeInferenceError(target=self,
                                                     attribute=name,
                                                     context=context)
Example #17
0
    def igetattr(self, name, context=None):
        """Retrieve the inferred values of the given attribute name."""

        if name in self.special_attributes:
            yield self.special_attributes.lookup(name)
            return

        try:
            mro = self.super_mro()
        # Don't let invalid MROs or invalid super calls
        # leak out as is from this function.
        except exceptions.SuperError as exc:
            util.reraise(exceptions.AttributeInferenceError(
                ('Lookup for {name} on {target!r} because super call {super!r} '
                 'is invalid.'),
                target=self, attribute=name, context=context, super_=exc.super_))
        except exceptions.MroError as exc:
            util.reraise(exceptions.AttributeInferenceError(
                ('Lookup for {name} on {target!r} failed because {cls!r} has an '
                 'invalid MRO.'),
                target=self, attribute=name, context=context, mros=exc.mros,
                cls=exc.cls))
        found = False
        for cls in mro:
            if name not in cls.locals:
                continue

            found = True
            for inferred in bases._infer_stmts([cls[name]], context, frame=self):
                if not isinstance(inferred, scoped_nodes.FunctionDef):
                    yield inferred
                    continue

                # We can obtain different descriptors from a super depending
                # on what we are accessing and where the super call is.
                if inferred.type == 'classmethod':
                    yield bases.BoundMethod(inferred, cls)
                elif self._scope.type == 'classmethod' and inferred.type == 'method':
                    yield inferred
                elif self._class_based or inferred.type == 'staticmethod':
                    yield inferred
                elif bases._is_property(inferred):
                    # TODO: support other descriptors as well.
                    for value in inferred.infer_call_result(self, context):
                        yield value
                else:
                    yield bases.BoundMethod(inferred, cls)

        if not found:
            raise exceptions.AttributeInferenceError(target=self,
                                                     attribute=name,
                                                     context=context)
Example #18
0
def infer_assign(
    self: nodes.AssignName | nodes.AssignAttr,
    context: InferenceContext | None = None,
    **kwargs: Any,
) -> Generator[InferenceResult, None, None]:
    """infer a AssignName/AssignAttr: need to inspect the RHS part of the
    assign node
    """
    if isinstance(self.parent, nodes.AugAssign):
        return self.parent.infer(context)

    stmts = list(self.assigned_stmts(context=context))
    return bases._infer_stmts(stmts, context)
Example #19
0
def infer_global(self: nodes.Global,
                 context: InferenceContext | None = None,
                 **kwargs: Any) -> Generator[InferenceResult, None, None]:
    if context is None or context.lookupname is None:
        raise InferenceError(node=self, context=context)
    try:
        return bases._infer_stmts(self.root().getattr(context.lookupname),
                                  context)
    except AttributeInferenceError as error:
        raise InferenceError(str(error),
                             target=self,
                             attribute=context.lookupname,
                             context=context) from error
Example #20
0
def infer_name(self, context=None):
    """infer a Name: use name lookup rules"""
    frame, stmts = self.lookup(self.name)
    if not stmts:
        # Try to see if the name is enclosed in a nested function
        # and use the higher (first function) scope for searching.
        # TODO: should this be promoted to other nodes as well?
        parent_function = _higher_function_scope(self.scope())
        if parent_function:
            _, stmts = parent_function.lookup(self.name)

        if not stmts:
            raise UnresolvableName(self.name)
    return _infer_stmts(stmts, context, frame, self.name)
Example #21
0
def infer_from(self, context=None, asname=True):
    """infer a From nodes: return the imported module/object"""
    name = context.lookupname
    if name is None:
        raise InferenceError()
    if asname:
        name = self.real_name(name)
    module = self.do_import_module(self.modname)
    try:
        context = copy_context(context)
        context.lookupname = name
        return _infer_stmts(module.getattr(name, ignore_locals=module is self.root()), context)
    except NotFoundError:
        raise InferenceError(name)
Example #22
0
def infer_import_from(self, context=None, asname=True):
    """infer a ImportFrom node: return the imported module/object"""
    name = context.lookupname
    if name is None:
        raise exceptions.InferenceError()
    if asname:
        name = self.real_name(name)
    module = self.do_import_module()
    try:
        context = contextmod.copy_context(context)
        context.lookupname = name
        stmts = module.getattr(name, ignore_locals=module is self.root())
        return bases._infer_stmts(stmts, context)
    except exceptions.NotFoundError:
        raise exceptions.InferenceError(name)
Example #23
0
def infer_from(self, context=None, asname=True):
    """infer a From nodes: return the imported module/object"""
    name = context.lookupname
    if name is None:
        raise InferenceError()
    if asname:
        name = self.real_name(name)
    module = self.do_import_module(self.modname)
    try:
        context = copy_context(context)
        context.lookupname = name
        return _infer_stmts(
            module.getattr(name, ignore_locals=module is self.root()), context)
    except NotFoundError:
        raise InferenceError(name)
Example #24
0
def infer_name(self, context=None):
    """infer a Name: use name lookup rules"""
    frame, stmts = self.lookup(self.name)
    if not stmts:
        # Try to see if the name is enclosed in a nested function
        # and use the higher (first function) scope for searching.
        parent_function = _higher_function_scope(self.scope())
        if parent_function:
            _, stmts = parent_function.lookup(self.name)

        if not stmts:
            raise exceptions.NameInferenceError(name=self.name,
                                                scope=self.scope(),
                                                context=context)
    context = context.clone()
    context.lookupname = self.name
    return bases._infer_stmts(stmts, context, frame)
Example #25
0
def infer_name(self, context=None):
    """infer a Name: use name lookup rules"""
    frame, stmts = self.lookup(self.name)
    if not stmts:
        # Try to see if the name is enclosed in a nested function
        # and use the higher (first function) scope for searching.
        parent_function = _higher_function_scope(self.scope())
        if parent_function:
            _, stmts = parent_function.lookup(self.name)

        if not stmts:
            raise exceptions.NameInferenceError(name=self.name,
                                                scope=self.scope(),
                                                context=context)
    context = contextmod.copy_context(context)
    context.lookupname = self.name
    return bases._infer_stmts(stmts, context, frame)
Example #26
0
    def igetattr(self, name, context=None):
        """Retrieve the inferred values of the given attribute name."""

        local_name = self._model.get(name)
        if local_name:
            yield local_name
            return

        try:
            mro = self.super_mro()
        except (MroError, SuperError) as exc:
            # Don't let invalid MROs or invalid super calls
            # to leak out as is from this function.
            six.raise_from(NotFoundError, exc)

        found = False
        for cls in mro:
            if name not in cls._locals:
                continue

            found = True
            for infered in _infer_stmts([cls[name]], context, frame=self):
                if not isinstance(infered, FunctionDef):
                    yield infered
                    continue

                # We can obtain different descriptors from a super depending
                # on what we are accessing and where the super call is.
                if infered.type == 'classmethod':
                    yield BoundMethod(infered, cls)
                elif self._scope.type == 'classmethod' and infered.type == 'method':
                    yield infered
                elif self._class_based or infered.type == 'staticmethod':
                    yield infered
                elif _is_property(infered):
                    # TODO: support other descriptors as well.
                    for value in infered.infer_call_result(self, context):
                        yield value
                else:
                    yield BoundMethod(infered, cls)

        if not found:
            raise NotFoundError(name)
Example #27
0
    def igetattr(self, name, context=None):
        """Retrieve the inferred values of the given attribute name."""

        local_name = self._model.get(name)
        if local_name:
            yield local_name
            return

        try:
            mro = self.super_mro()
        except (MroError, SuperError) as exc:
            # Don't let invalid MROs or invalid super calls
            # to leak out as is from this function.
            six.raise_from(NotFoundError, exc)

        found = False
        for cls in mro:
            if name not in cls._locals:
                continue

            found = True
            for infered in _infer_stmts([cls[name]], context, frame=self):
                if not isinstance(infered, FunctionDef):
                    yield infered
                    continue

                # We can obtain different descriptors from a super depending
                # on what we are accessing and where the super call is.
                if infered.type == 'classmethod':
                    yield BoundMethod(infered, cls)
                elif self._scope.type == 'classmethod' and infered.type == 'method':
                    yield infered
                elif self._class_based or infered.type == 'staticmethod':
                    yield infered
                elif _is_property(infered):
                    # TODO: support other descriptors as well.
                    for value in infered.infer_call_result(self, context):
                        yield value
                else:
                    yield BoundMethod(infered, cls)

        if not found:
            raise NotFoundError(name)
Example #28
0
def infer_name(
    self: nodes.Name | nodes.AssignName,
    context: InferenceContext | None = None,
    **kwargs: Any,
) -> Generator[InferenceResult, None, None]:
    """infer a Name: use name lookup rules"""
    frame, stmts = self.lookup(self.name)
    if not stmts:
        # Try to see if the name is enclosed in a nested function
        # and use the higher (first function) scope for searching.
        parent_function = _higher_function_scope(self.scope())
        if parent_function:
            _, stmts = parent_function.lookup(self.name)

        if not stmts:
            raise NameInferenceError(name=self.name,
                                     scope=self.scope(),
                                     context=context)
    context = copy_context(context)
    context.lookupname = self.name
    return bases._infer_stmts(stmts, context, frame)
Example #29
0
def infer_import_from(self, context=None, asname=True):
    """infer a ImportFrom node: return the imported module/object"""
    name = context.lookupname
    if name is None:
        raise exceptions.InferenceError(node=self, context=context)
    if asname:
        name = self.real_name(name)

    try:
        module = self.do_import_module()
    except exceptions.AstroidBuildingError as exc:
        raise exceptions.InferenceError(node=self, context=context) from exc

    try:
        context = contextmod.copy_context(context)
        context.lookupname = name
        stmts = module.getattr(name, ignore_locals=module is self.root())
        return bases._infer_stmts(stmts, context)
    except exceptions.AttributeInferenceError as error:
        raise exceptions.InferenceError(
            error.message, target=self, attribute=name, context=context
        ) from error
Example #30
0
    def igetattr(self, name: str, context: InferenceContext | None = None):
        """Retrieve the inferred values of the given attribute name."""
        # '__class__' is a special attribute that should be taken directly
        # from the special attributes dict
        if name == "__class__":
            yield self.special_attributes.lookup(name)
            return

        try:
            mro = self.super_mro()
        # Don't let invalid MROs or invalid super calls
        # leak out as is from this function.
        except SuperError as exc:
            raise AttributeInferenceError(
                ("Lookup for {name} on {target!r} because super call {super!r} "
                 "is invalid."),
                target=self,
                attribute=name,
                context=context,
                super_=exc.super_,
            ) from exc
        except MroError as exc:
            raise AttributeInferenceError(
                ("Lookup for {name} on {target!r} failed because {cls!r} has an "
                 "invalid MRO."),
                target=self,
                attribute=name,
                context=context,
                mros=exc.mros,
                cls=exc.cls,
            ) from exc
        found = False
        for cls in mro:
            if name not in cls.locals:
                continue

            found = True
            for inferred in bases._infer_stmts([cls[name]],
                                               context,
                                               frame=self):
                if not isinstance(inferred, scoped_nodes.FunctionDef):
                    yield inferred
                    continue

                # We can obtain different descriptors from a super depending
                # on what we are accessing and where the super call is.
                if inferred.type == "classmethod":
                    yield bases.BoundMethod(inferred, cls)
                elif self._scope.type == "classmethod" and inferred.type == "method":
                    yield inferred
                elif self._class_based or inferred.type == "staticmethod":
                    yield inferred
                elif isinstance(inferred, Property):
                    function = inferred.function
                    try:
                        yield from function.infer_call_result(caller=self,
                                                              context=context)
                    except InferenceError:
                        yield util.Uninferable
                elif bases._is_property(inferred):
                    # TODO: support other descriptors as well.
                    try:
                        yield from inferred.infer_call_result(self, context)
                    except InferenceError:
                        yield util.Uninferable
                else:
                    yield bases.BoundMethod(inferred, cls)

        # Only if we haven't found any explicit overwrites for the
        # attribute we look it up in the special attributes
        if not found and name in self.special_attributes:
            yield self.special_attributes.lookup(name)
            return

        if not found:
            raise AttributeInferenceError(target=self,
                                          attribute=name,
                                          context=context)