How to use the astroid.node_classes 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_nodes.py View on Github external
code = """
            try:
                from pickle import PickleError
            except ImportError:
                from nonexistent import PickleError

            try:
                pass
            except PickleError:
                pass
        """
        module = builder.parse(code)
        handler_type = module.body[1].handlers[0].type

        excs = list(node_classes.unpack_infer(handler_type))
        # The number of returned object can differ on Python 2
        # and Python 3. In one version, an additional item will
        # be returned, from the _pickle module, which is not
        # present in the other version.
        self.assertIsInstance(excs[0], nodes.ClassDef)
        self.assertEqual(excs[0].name, "PickleError")
        self.assertIs(excs[-1], util.Uninferable)
github PyCQA / astroid / astroid / interpreter / objectmodel.py View on Github external
from astroid import scoped_nodes

        if not self._instance.newstyle:
            raise exceptions.AttributeInferenceError(
                target=self._instance, attribute="__subclasses__"
            )

        qname = self._instance.qname()
        root = self._instance.root()
        classes = [
            cls
            for cls in root.nodes_of_class(scoped_nodes.ClassDef)
            if cls != self._instance and cls.is_subtype_of(qname)
        ]

        obj = node_classes.List(parent=self._instance)
        obj.postinit(classes)

        class SubclassesBoundMethod(bases.BoundMethod):
            def infer_call_result(self, caller, context=None):
                yield obj

        implicit_metaclass = self._instance.implicit_metaclass()
        subclasses_method = implicit_metaclass.locals["__subclasses__"][0]
        return SubclassesBoundMethod(proxy=subclasses_method, bound=implicit_metaclass)
github ethanchewy / PythonBuddy / venv / lib / python2.7 / site-packages / astroid / scoped_nodes.py View on Github external
- the only statement is 'raise NotImplementedError', or
         - the only statement is 'pass' and pass_is_abstract is True, or
         - the method is annotated with abc.astractproperty/abc.abstractmethod
        """
        if self.decorators:
            for node in self.decorators.nodes:
                try:
                    inferred = next(node.infer())
                except exceptions.InferenceError:
                    continue
                if inferred and inferred.qname() in ('abc.abstractproperty',
                                                     'abc.abstractmethod'):
                    return True

        for child_node in self.body:
            if isinstance(child_node, node_classes.Raise):
                if child_node.raises_not_implemented():
                    return True
            return pass_is_abstract and isinstance(child_node, node_classes.Pass)
        # empty function is the same as function with a single "pass" statement
        if pass_is_abstract:
            return True
github PyCQA / pylint / pylint / checkers / refactoring.py View on Github external
def _is_simple_assignment(node):
        return (
            isinstance(node, astroid.Assign)
            and len(node.targets) == 1
            and isinstance(node.targets[0], astroid.node_classes.AssignName)
            and isinstance(node.value, astroid.node_classes.Name)
        )
github PyCQA / astroid / astroid / scoped_nodes.py View on Github external
class_bases = next(caller.args[1].infer(context))
        if isinstance(class_bases, (node_classes.Tuple, node_classes.List)):
            result.bases = class_bases.itered()
        else:
            # There is currently no AST node that can represent an 'unknown'
            # node (Uninferable is not an AST node), therefore we simply return Uninferable here
            # although we know at least the name of the class.
            return util.Uninferable

        # Get the members of the class
        try:
            members = next(caller.args[2].infer(context))
        except exceptions.InferenceError:
            members = None

        if members and isinstance(members, node_classes.Dict):
            for attr, value in members.items:
                if (isinstance(attr, node_classes.Const) and
                        isinstance(attr.value, six.string_types)):
                    result.locals[attr.value] = [value]

        result.parent = caller.parent
        return result
github PyCQA / astroid / astroid / objects.py View on Github external
class FrozenSet(node_classes._BaseContainer):
    """class representing a FrozenSet composite node"""

    def pytype(self):
        return "%s.frozenset" % BUILTINS

    def _infer(self, context=None):
        yield self

    @decorators.cachedproperty
    def _proxied(self):  # pylint: disable=method-hidden
        ast_builtins = MANAGER.builtins_module
        return ast_builtins.getattr("frozenset")[0]


class Super(node_classes.NodeNG):
    """Proxy class over a super call.

    This class offers almost the same behaviour as Python's super,
    which is MRO lookups for retrieving attributes from the parents.

    The *mro_pointer* is the place in the MRO from where we should
    start looking, not counting it. *mro_type* is the object which
    provides the MRO, it can be both a type or an instance.
    *self_class* is the class where the super call is, while
    *scope* is the function where the super call is.
    """

    # pylint: disable=unnecessary-lambda
    special_attributes = util.lazy_descriptor(lambda: objectmodel.SuperModel())

    # pylint: disable=super-init-not-called
github PyCQA / pylint / pylint / checkers / typecheck.py View on Github external
if not isinstance(node.target, astroid.node_classes.Tuple):
            # target is not a tuple
            return
        if not len(node.target.elts) == 2:
            # target is not a tuple of two elements
            return

        iterable = node.iter
        if not isinstance(iterable, astroid.node_classes.Name):
            # it's not a bare variable
            return

        inferred = safe_infer(iterable)
        if not inferred:
            return
        if not isinstance(inferred, astroid.node_classes.Dict):
            # the iterable is not a dict
            return

        self.add_message("dict-iter-missing-items", node=node)
github marslo / myvim / Configurations / Offline_Packages / bundle / python-mode / pymode / libs / astroid / scoped_nodes.py View on Github external
We consider that a class wraps a node if the class
    is a parent for the said node.
    """

    klass = node.frame()
    while klass is not None and not isinstance(klass, ClassDef):
        if klass.parent is None:
            klass = None
        else:
            klass = klass.parent.frame()
    return klass



class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
               node_classes.Statement):

    # some of the attributes below are set by the builder module or
    # by a raw factories

    # a dictionary of class instances attributes
    _astroid_fields = ('decorators', 'bases', 'body') # name

    decorators = None
    special_attributes = objectmodel.ClassModel()

    _type = None
    _metaclass_hack = False
    hide = False
    type = property(_class_type,
                    doc="class'type, possible values are 'class' | "
                    "'metaclass' | 'exception'")
github PyCQA / astroid / astroid / scoped_nodes.py View on Github external
The property will return all the callables that are used for
        decoration.

        :type: list(NodeNG)
        """
        frame = self.parent.frame()
        if not isinstance(frame, ClassDef):
            return []

        decorators = []
        for assign in frame._get_assign_nodes():
            if isinstance(assign.value, node_classes.Call) and isinstance(
                assign.value.func, node_classes.Name
            ):
                for assign_node in assign.targets:
                    if not isinstance(assign_node, node_classes.AssignName):
                        # Support only `name = callable(name)`
                        continue

                    if assign_node.name != self.name:
                        # Interested only in the assignment nodes that
                        # decorates the current method.
                        continue
                    try:
                        meth = frame[self.name]
                    except KeyError:
                        continue
                    else:
                        # Must be a function and in the same frame as the
                        # original method.
                        if (
                            isinstance(meth, FunctionDef)
github PyCQA / astroid / astroid / raw_building.py View on Github external
def _astroid_bootstrapping(astroid_builtin=None):
    """astroid boot strapping the builtins module"""
    # this boot strapping is necessary since we need the Const nodes to
    # inspect_build builtins, and then we can proxy Const
    if astroid_builtin is None:
        astroid_builtin = Astroid_BUILDER.inspect_build(builtins)

    # pylint: disable=redefined-outer-name
    for cls, node_cls in node_classes.CONST_CLS.items():
        if cls is type(None):
            proxy = build_class("NoneType", parent=astroid_builtin)
        elif cls is type(NotImplemented):
            proxy = build_class("NotImplementedType", parent=astroid_builtin)
        else:
            proxy = astroid_builtin.getattr(cls.__name__)[0]
        if cls in (dict, list, set, tuple):
            node_cls._proxied = proxy
        else:
            _CONST_PROXY[cls] = proxy