How to use the astroid.bases.Instance 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 / test / unittest_inference.py View on Github external
return active_application

class Application(object):
  def __init__(self):
     global active_application
     active_application = self

class DataManager(object):
  def __init__(self, app=None):
     self.app = get_active_application()
  def test(self):
     p = self.app
     print (p)
        '''
        astroid = builder.string_build(code, __name__, __file__)
        infered = list(Instance(astroid['DataManager']).igetattr('app'))
        self.assertEqual(len(infered), 2, infered) # None / Instance(Application)
        infered = list(get_name_node(astroid['DataManager']['test'], 'p').infer())
        self.assertEqual(len(infered), 2, infered)
        for node in infered:
            if isinstance(node, Instance) and node.name == 'Application':
                break
        else:
            self.fail('expected to find an instance of Application in %s' % infered)
github svn2github / chromium-depot-tools / third_party / logilab / astroid / scoped_nodes.py View on Github external
def interfaces(self, herited=True, handler_func=_iface_hdlr):
        """return an iterator on interfaces implemented by the given
        class node
        """
        # FIXME: what if __implements__ = (MyIFace, MyParent.__implements__)...
        try:
            implements = Instance(self).getattr('__implements__')[0]
        except NotFoundError:
            return
        if not herited and not implements.frame() is self:
            return
        found = set()
        missing = False
        for iface in unpack_infer(implements):
            if iface is YES:
                missing = True
                continue
            if not iface in found and handler_func(iface):
                found.add(iface)
                yield iface
        if missing:
            raise InferenceError()
github svn2github / chromium-depot-tools / third_party / logilab / astroid / scoped_nodes.py View on Github external
yield YES
                return
            result = Class(name, None)
            bases = next(caller.args[1].infer(context))
            if isinstance(bases, (Tuple, List)):
                result.bases = bases.itered()
            else:
                # There is currently no AST node that can represent an 'unknown'
                # node (YES is not an AST node), therefore we simply return YES here
                # although we know at least the name of the class.
                yield YES
                return
            result.parent = caller.parent
            yield result
        else:
            yield Instance(self)
github pylava / pylava_pylint / pylama_pylint / astroid / inference.py View on Github external
try:
            return self.nargs[name].infer(context)
        except KeyError:
            # Function.args.args can be None in astroid (means that we don't have
            # information on argnames)
            argindex = funcnode.args.find_argname(name)[0]
            if argindex is not None:
                # 2. first argument of instance/class method
                if argindex == 0 and funcnode.type in ('method', 'classmethod'):
                    if context.boundnode is not None:
                        boundnode = context.boundnode
                    else:
                        # XXX can do better ?
                        boundnode = funcnode.parent.frame()
                    if funcnode.type == 'method':
                        if not isinstance(boundnode, Instance):
                            boundnode = Instance(boundnode)
                        return iter((boundnode,))
                    if funcnode.type == 'classmethod':
                        return iter((boundnode,))
                # if we have a method, extract one position
                # from the index, so we'll take in account
                # the extra parameter represented by `self` or `cls`
                if funcnode.type in ('method', 'classmethod'):
                    argindex -= 1
                # 2. search arg index
                try:
                    return self.args[argindex].infer(context)
                except IndexError:
                    pass
                # 3. search in *args (.starargs)
                if self.starargs is not None:
github PyCQA / astroid / astroid / builder.py View on Github external
def delayed_assattr(self, node):
        """Visit a AssAttr node

        This adds name to locals and handle members definition.
        """
        try:
            frame = node.frame()
            for inferred in node.expr.infer():
                if inferred is util.Uninferable:
                    continue
                try:
                    if inferred.__class__ is bases.Instance:
                        inferred = inferred._proxied
                        iattrs = inferred.instance_attrs
                        if not _can_assign_attr(inferred, node.attrname):
                            continue
                    elif isinstance(inferred, bases.Instance):
                        # Const, Tuple, ... we may be wrong, may be not, but
                        # anyway we don't want to pollute builtin's namespace
                        continue
                    elif inferred.is_function:
                        iattrs = inferred.instance_attrs
                    else:
                        iattrs = inferred.locals
                except AttributeError:
                    # XXX log error
                    continue
                values = iattrs.setdefault(node.attrname, [])
github marslo / myvim / Configurations / Offline_Packages / bundle / python-mode / pymode / libs / pylint / pyreverse / inspector.py View on Github external
def interfaces(node, herited=True, handler_func=_iface_hdlr):
    """Return an iterator on interfaces implemented by the given class node."""
    # FIXME: what if __implements__ = (MyIFace, MyParent.__implements__)...
    try:
        implements = bases.Instance(node).getattr('__implements__')[0]
    except exceptions.NotFoundError:
        return
    if not herited and implements.frame() is not node:
        return
    found = set()
    missing = False
    for iface in node_classes.unpack_infer(implements):
        if iface is astroid.YES:
            missing = True
            continue
        if iface not in found and handler_func(iface):
            found.add(iface)
            yield iface
    if missing:
        raise exceptions.InferenceError()
github gtt116 / vimrc / vim / bundle / python-mode / submodules / pylint / pylint / pyreverse / inspector.py View on Github external
def interfaces(node, herited=True, handler_func=_iface_hdlr):
    """Return an iterator on interfaces implemented by the given class node."""
    # FIXME: what if __implements__ = (MyIFace, MyParent.__implements__)...
    try:
        implements = bases.Instance(node).getattr('__implements__')[0]
    except exceptions.NotFoundError:
        return
    if not herited and implements.frame() is not node:
        return
    found = set()
    missing = False
    for iface in node_classes.unpack_infer(implements):
        if iface is astroid.Uninferable:
            missing = True
            continue
        if iface not in found and handler_func(iface):
            found.add(iface)
            yield iface
    if missing:
        raise exceptions.InferenceError()
github pylava / pylava_pylint / pylama_pylint / astroid / inference.py View on Github external
return self.nargs[name].infer(context)
        except KeyError:
            # Function.args.args can be None in astroid (means that we don't have
            # information on argnames)
            argindex = funcnode.args.find_argname(name)[0]
            if argindex is not None:
                # 2. first argument of instance/class method
                if argindex == 0 and funcnode.type in ('method', 'classmethod'):
                    if context.boundnode is not None:
                        boundnode = context.boundnode
                    else:
                        # XXX can do better ?
                        boundnode = funcnode.parent.frame()
                    if funcnode.type == 'method':
                        if not isinstance(boundnode, Instance):
                            boundnode = Instance(boundnode)
                        return iter((boundnode,))
                    if funcnode.type == 'classmethod':
                        return iter((boundnode,))
                # if we have a method, extract one position
                # from the index, so we'll take in account
                # the extra parameter represented by `self` or `cls`
                if funcnode.type in ('method', 'classmethod'):
                    argindex -= 1
                # 2. search arg index
                try:
                    return self.args[argindex].infer(context)
                except IndexError:
                    pass
                # 3. search in *args (.starargs)
                if self.starargs is not None:
                    its = []
github ethanchewy / PythonBuddy / venv / lib / python2.7 / site-packages / astroid / objects.py View on Github external
from astroid import MANAGER
from astroid.bases import (
    BUILTINS, NodeNG, Instance, _infer_stmts,
    BoundMethod, _is_property
)
from astroid.decorators import cachedproperty
from astroid.exceptions import (
    SuperError, SuperArgumentTypeError,
    NotFoundError, MroError
)
from astroid.node_classes import const_factory
from astroid.scoped_nodes import ClassDef, FunctionDef
from astroid.mixins import ParentAssignTypeMixin


class FrozenSet(NodeNG, Instance, ParentAssignTypeMixin):
    """class representing a FrozenSet composite node"""

    def __init__(self, elts=None):
        if elts is None:
            self.elts = []
        else:
            self.elts = [const_factory(e) for e in elts]

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

    def itered(self):
        return self.elts

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