How to use the astroid.util function in astroid

To help you get started, we’ve selected a few astroid examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github PyCQA / astroid / tests / unittest_brain.py View on Github external
def test_1(self):
        node = builder.extract_node(
            """
        from collections import defaultdict

        X = defaultdict(int)
        X[0]
        """
        )
        inferred = next(node.infer())
        self.assertIs(util.Uninferable, inferred)
github ethanchewy / PythonBuddy / venv / lib / python2.7 / site-packages / astroid / protocols.py View on Github external
"""recursive function to resolve multiple assignments"""
    asspath = asspath[:]
    index = asspath.pop(0)
    for part in parts:
        if hasattr(part, 'getitem'):
            try:
                assigned = part.getitem(index, context)
            # XXX raise a specific exception to avoid potential hiding of
            # unexpected exception ?
            except (TypeError, IndexError):
                return
            if not asspath:
                # we achieved to resolved the assignment path, don't infer the
                # last part
                yield assigned
            elif assigned is util.YES:
                return
            else:
                # we are not yet on the last part of the path search on each
                # possibly inferred value
                try:
                    for inferred in _resolve_asspart(assigned.infer(context),
                                                    asspath, context):
                        yield inferred
                except exceptions.InferenceError:
                    return
github PyCQA / astroid / astroid / builder.py View on Github external
import os
import textwrap
from tokenize import detect_encoding

from astroid._ast import _parse
from astroid import bases
from astroid import exceptions
from astroid import manager
from astroid import modutils
from astroid import raw_building
from astroid import rebuilder
from astroid import nodes
from astroid import util

objects = util.lazy_import("objects")

# The name of the transient function that is used to
# wrap expressions to be extracted when calling
# extract_node.
_TRANSIENT_FUNCTION = "__"

# The comment used to select a statement to be extracted
# when calling extract_node.
_STATEMENT_SELECTOR = "#@"

MANAGER = manager.AstroidManager()


def open_source_file(filename):
    with open(filename, "rb") as byte_stream:
        encoding = detect_encoding(byte_stream.readline)[0]
github PyCQA / astroid / astroid / scoped_nodes.py View on Github external
# set lookup name since this is necessary to infer on import nodes for
        # instance
        context = contextmod.copy_context(context)
        context.lookupname = name
        try:
            attrs = self.getattr(name, context, class_context=class_context)
            for inferred in bases._infer_stmts(attrs, context, frame=self):
                # yield Uninferable object instead of descriptors when necessary
                if (not isinstance(inferred, node_classes.Const)
                        and isinstance(inferred, bases.Instance)):
                    try:
                        inferred._proxied.getattr('__get__', context)
                    except exceptions.AttributeInferenceError:
                        yield inferred
                    else:
                        yield util.Uninferable
                else:
                    yield function_to_method(inferred, self)
        except exceptions.AttributeInferenceError as error:
            if not name.startswith('__') and self.has_dynamic_getattr(context):
                # class handle some dynamic attributes, return a Uninferable object
                yield util.Uninferable
            else:
                util.reraise(exceptions.InferenceError(
                    error.message, target=self, attribute=name, context=context))
github PyCQA / astroid / astroid / node_classes.py View on Github external
"""Get a slice or an item, using the given *index*, for the given sequence."""
    try:
        if isinstance(index, Slice):
            index_slice = _infer_slice(index, context=context)
            new_cls = instance.__class__()
            new_cls.elts = elts[index_slice]
            new_cls.parent = instance.parent
            return new_cls
        elif isinstance(index, Const):
            return elts[index.value]
    except IndexError:
        util.reraise(exceptions.AstroidIndexError(
            message='Index {index!s} out of range',
            node=instance, index=index, context=context))
    except TypeError as exc:
        util.reraise(exceptions.AstroidTypeError(
            message='Type error {error!r}', error=exc,
            node=instance, index=index, context=context))

    raise exceptions.AstroidTypeError(
        'Could not use %s as subscript index' % index
    )
github marslo / myvim / Configurations / Offline_Packages / bundle / python-mode / pymode / libs / astroid / scoped_nodes.py View on Github external
def igetattr(self, name, context=None):
        """Inferred getattr, which returns an iterator of inferred statements."""
        try:
            return bases._infer_stmts(self.getattr(name, context),
                                      context, frame=self)
        except exceptions.AttributeInferenceError as error:
            util.reraise(exceptions.InferenceError(
                error.message, target=self, attribute=name, context=context))
github marslo / myvim / Configurations / Offline_Packages / bundle / python-mode / pymode / libs / astroid / brain / brain_builtin_inference.py View on Github external
# Invalid bool call.
        raise UseInferenceDefault

    if not node.args:
        return nodes.Const(False)

    argument = node.args[0]
    try:
        inferred = next(argument.infer(context=context))
    except InferenceError:
        return util.Uninferable
    if inferred is util.Uninferable:
        return util.Uninferable

    bool_value = inferred.bool_value()
    if bool_value is util.Uninferable:
        return util.Uninferable
    return nodes.Const(bool_value)
github PyCQA / astroid / astroid / node_classes.py View on Github external
def type_errors(self, context=None):
        """Get a list of type errors which can occur during inference.

        Each TypeError is represented by a :class:`BadBinaryOperationMessage`,
        which holds the original exception.

        :returns: The list of possible type errors.
        :rtype: list(BadBinaryOperationMessage)
        """
        try:
            results = self._infer_unaryop(context=context)
            return [result for result in results
                    if isinstance(result, util.BadUnaryOperationMessage)]
        except exceptions.InferenceError:
            return []
github ethanchewy / PythonBuddy / venv / lib / python2.7 / site-packages / astroid / brain / brain_builtin_inference.py View on Github external
def _generic_inference(node, context, node_type, transform):
    args = node.args
    if not args:
        return node_type()
    if len(node.args) > 1:
        raise UseInferenceDefault()

    arg, = args
    transformed = transform(arg)
    if not transformed:
        try:
            inferred = next(arg.infer(context=context))
        except (InferenceError, StopIteration):
            raise UseInferenceDefault()
        if inferred is util.YES:
            raise UseInferenceDefault()
        transformed = transform(inferred)
    if not transformed or transformed is util.YES:
        raise UseInferenceDefault()
    return transformed
github PyCQA / astroid / astroid / bases.py View on Github external
# Get the method from the instance and try to infer
    # its return's truth value.
    meth = next(instance.igetattr(method_name, context=context), None)
    if meth and hasattr(meth, "infer_call_result"):
        if not meth.callable():
            return util.Uninferable
        try:
            for value in meth.infer_call_result(instance, context=context):
                if value is util.Uninferable:
                    return value

                inferred = next(value.infer(context=context))
                return inferred.bool_value()
        except exceptions.InferenceError:
            pass
    return util.Uninferable