How to use the astroid.nodes 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
six.moves.http_client #@
        six.moves.urllib_parse #@
        six.moves.urllib_error #@
        six.moves.urllib.request #@
        """
        )
        http_client = next(ast_nodes[0].infer())
        self.assertIsInstance(http_client, nodes.Module)
        self.assertEqual(http_client.name, "http.client")

        urllib_parse = next(ast_nodes[1].infer())
        self.assertIsInstance(urllib_parse, nodes.Module)
        self.assertEqual(urllib_parse.name, "urllib.parse")
        urljoin = next(urllib_parse.igetattr("urljoin"))
        urlencode = next(urllib_parse.igetattr("urlencode"))
        self.assertIsInstance(urljoin, nodes.FunctionDef)
        self.assertEqual(urljoin.qname(), "urllib.parse.urljoin")
        self.assertIsInstance(urlencode, nodes.FunctionDef)
        self.assertEqual(urlencode.qname(), "urllib.parse.urlencode")

        urllib_error = next(ast_nodes[2].infer())
        self.assertIsInstance(urllib_error, nodes.Module)
        self.assertEqual(urllib_error.name, "urllib.error")
        urlerror = next(urllib_error.igetattr("URLError"))
        self.assertIsInstance(urlerror, nodes.ClassDef)
        content_too_short = next(urllib_error.igetattr("ContentTooShortError"))
        self.assertIsInstance(content_too_short, nodes.ClassDef)

        urllib_request = next(ast_nodes[3].infer())
        self.assertIsInstance(urllib_request, nodes.Module)
        self.assertEqual(urllib_request.name, "urllib.request")
        urlopen = next(urllib_request.igetattr("urlopen"))
github edx / edx-lint / test / utils.py View on Github external
def get_module(node):
    """Find the Module node from a child node."""
    while node.__class__ != astroid.nodes.Module:
        node = node.parent
    return node
github tophat / codewatch / tests / config_modules / integration_config.py View on Github external
    inferences=[inference(nodes.Call, infer_objects_get_as_a, is_a_object_get)]
)
def call_visitor(node, stats, _rel_file_path):
    inf_types = node.inferred()
    stats.append("inferred A.objects.get()", inf_types)
github ethanchewy / PythonBuddy / venv / lib / python2.7 / site-packages / astroid / rebuilder.py View on Github external
def visit_raise(self, node, parent, assign_ctx=None):
        """visit a Raise node by returning a fresh instance of it"""
        newnode = new.Raise()
        _lineno_parent(node, newnode, parent)
        # no traceback; anyway it is not used in Pylint
        if node.exc is not None:
            newnode.exc = self.visit(node.exc, newnode, assign_ctx)
        if node.cause is not None:
            newnode.cause = self.visit(node.cause, newnode, assign_ctx)
        return newnode
github marslo / myvim / Configurations / Offline_Packages / bundle / python-mode / pymode / libs / astroid / inference.py View on Github external
def _higher_function_scope(node):
    """ Search for the first function which encloses the given
    scope. This can be used for looking up in that function's
    scope, in case looking up in a lower scope for a particular
    name fails.

    :param node: A scope node.
    :returns:
        ``None``, if no parent function scope was found,
        otherwise an instance of :class:`astroid.scoped_nodes.Function`,
        which encloses the given node.
    """
    current = node
    while current.parent and not isinstance(current.parent, nodes.Function):
        current = current.parent
    if current and current.parent:
        return current.parent
github PyCQA / astroid / astroid / inference.py View on Github external
return stmt.infer(context)
    stmts = list(self.assigned_stmts(context=context))
    return _infer_stmts(stmts, context)
nodes.AssName._infer = path_wrapper(infer_ass)
nodes.AssAttr._infer = path_wrapper(infer_ass)

def infer_augassign(self, context=None):
    failures = []
    for lhs in self.target.infer_lhs(context):
        for val in _infer_binop(self.op, lhs, self.value, context, failures):
            yield val
    for lhs in failures:
        for rhs in self.value.infer(context):
            for val in _infer_binop(self.op, rhs, lhs, context):
                yield val
nodes.AugAssign._infer = path_wrapper(infer_augassign)


# no infer method on DelName and DelAttr (expected InferenceError)


def infer_empty_node(self, context=None):
    if not self.has_underlying_object():
        yield YES
    else:
        try:
            for infered in MANAGER.infer_ast_from_something(self.object,
                                                            context=context):
                yield infered
        except AstroidError:
            yield YES
nodes.EmptyNode._infer = path_wrapper(infer_empty_node)
github pylava / pylava_pylint / pylama_pylint / astroid / inference.py View on Github external
pass
        except AttributeError:
            # XXX method / function
            pass
nodes.Getattr._infer = path_wrapper(raise_if_nothing_infered(infer_getattr))
nodes.AssAttr.infer_lhs = raise_if_nothing_infered(infer_getattr) # # won't work with a path wrapper


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()
nodes.Global._infer = path_wrapper(infer_global)


def infer_subscript(self, context=None):
    """infer simple subscription such as [1,2,3][0] or (1,2,3)[-1]"""
    value = next(self.value.infer(context))
    if value is YES:
        yield YES
        return

    index = next(self.slice.infer(context))
    if index is YES:
        yield YES
        return

    if isinstance(index, nodes.Const):
        try:
github PyCQA / astroid / astroid / brain / brain_argparse.py View on Github external
def _looks_like_namespace(node):
    func = node.func
    if isinstance(func, nodes.Attribute):
        return (
            func.attrname == "Namespace"
            and isinstance(func.expr, nodes.Name)
            and func.expr.name == "argparse"
        )
    return False
github PyCQA / astroid / astroid / protocols.py View on Github external
"No decorators found on inferred generator %s", node=func
            )

        for decorator_node in func.decorators.nodes:
            decorator = next(decorator_node.infer(context=context))
            if isinstance(decorator, nodes.FunctionDef):
                if decorator.qname() == _CONTEXTLIB_MGR:
                    break
        else:
            # It doesn't interest us.
            raise exceptions.InferenceError(node=func)

        # Get the first yield point. If it has multiple yields,
        # then a RuntimeError will be raised.

        possible_yield_points = func.nodes_of_class(nodes.Yield)
        # Ignore yields in nested functions
        yield_point = next(
            (node for node in possible_yield_points if node.scope() == func), None
        )
        if yield_point:
            if not yield_point.value:
                const = nodes.Const(None)
                const.parent = yield_point
                const.lineno = yield_point.lineno
                yield const
            else:
                yield from yield_point.value.infer(context=context)
    elif isinstance(inferred, bases.Instance):
        try:
            enter = next(inferred.igetattr("__enter__", context=context))
        except (exceptions.InferenceError, exceptions.AttributeInferenceError):
github PyCQA / astroid / astroid / raw_building.py View on Github external
def build_function(name, args=None, posonlyargs=None, defaults=None, doc=None):
    """create and initialize an astroid FunctionDef node"""
    args, defaults, posonlyargs = args or [], defaults or [], posonlyargs or []
    # first argument is now a list of decorators
    func = nodes.FunctionDef(name, doc)
    func.args = argsnode = nodes.Arguments()
    argsnode.args = []
    argsnode.posonlyargs = []
    for arg in args:
        argsnode.args.append(nodes.Name())
        argsnode.args[-1].name = arg
        argsnode.args[-1].parent = argsnode
    for arg in posonlyargs:
        argsnode.posonlyargs.append(nodes.Name())
        argsnode.posonlyargs[-1].name = arg
        argsnode.posonlyargs[-1].parent = argsnode
    argsnode.defaults = []
    for default in defaults:
        argsnode.defaults.append(nodes.const_factory(default))
        argsnode.defaults[-1].parent = argsnode
    argsnode.kwarg = None
    argsnode.vararg = None