How to use the pytype.abstract.Instance function in pytype

To help you get started, weā€™ve selected a few pytype 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 google / pytype / pytype / attribute.py View on Github external
def _get_member(self, node, obj, name):
    """Get a member of an object."""
    if obj.is_lazy:
      obj.load_lazy_attribute(name)

    # If we are looking up a member that we can determine is an instance
    # rather than a class attribute, add it to the instance's members.
    if isinstance(obj, abstract.Instance):
      if name not in obj.members or not obj.members[name].bindings:
        # See test_generic.testInstanceAttributeVisible for an example of an
        # attribute in self.members needing to be reloaded.
        self._maybe_load_as_instance_attribute(node, obj, name)

    # Retrieve member
    if name in obj.members and obj.members[name].Bindings(node):
      return node, obj.members[name]
    return node, None
github google / pytype / pytype / convert.py View on Github external
self.false = abstract.AbstractOrConcreteValue(
        False, self.primitive_classes[bool], self.vm)
    self.ellipsis = abstract.AbstractOrConcreteValue(
        Ellipsis, self.primitive_classes[compat.EllipsisType], self.vm)

    self.primitive_class_instances = {}
    for name, cls in self.primitive_classes.items():
      if name == compat.NoneType:
        # This is possible because all None instances are the same.
        # Without it pytype could not reason that "x is None" is always true, if
        # x is indeed None.
        instance = self.none
      elif name == compat.EllipsisType:
        instance = self.ellipsis
      else:
        instance = abstract.Instance(cls, self.vm)
      self.primitive_class_instances[name] = instance
      self._convert_cache[(abstract.Instance, cls.pytd_cls)] = instance

    self.none_type = self.primitive_classes[compat.NoneType]
    self.oldstyleclass_type = self.primitive_classes[compat.OldStyleClassType]
    self.super_type = self.primitive_classes[super]
    self.str_type = self.primitive_classes[str]
    self.int_type = self.primitive_classes[int]

    self.list_type = self.constant_to_value(list)
    self.set_type = self.constant_to_value(set)
    self.frozenset_type = self.constant_to_value(frozenset)
    self.dict_type = self.constant_to_value(dict)
    self.type_type = self.constant_to_value(type)
    self.module_type = self.constant_to_value(types.ModuleType)
    self.function_type = self.constant_to_value(types.FunctionType)
github google / pytype / pytype / analyze.py View on Github external
def create_varargs(self, node):
    value = abstract.Instance(self.convert.tuple_type, self)
    value.initialize_type_parameter(
        abstract.T, self.convert.create_new_unknown(node))
    return value.to_variable(node)
github google / pytype / pytype / abstract.py View on Github external
# class Foo(List[int]), or a non-1:1 parameter mapping, e.g.,
            # class Foo(List[K or V]). Initialize the corresponding instance
            # parameter appropriately.
            lazy_value = (param.instantiate, self.vm.root_cfg_node, self)
            if name not in self.type_parameters:
              self.type_parameters.add_lazy_item(name, *lazy_value)
            elif not self.type_parameters.lazy_eq(name, *lazy_value):
              # Two unrelated containers happen to use the same type
              # parameter name. pytype isn't yet smart enough to handle this
              # case, so we'll just set the type parameter to Any.
              bad_names.add(name)
    # We can't reliably track changes to type parameters involved in naming
    # conflicts, so we'll set all of them to unsolvable.
    node = self.vm.root_cfg_node
    for name in bad_names:
      super(Instance, self).merge_type_parameter(
          node, name, self.vm.convert.create_new_unsolvable(node))
    self._bad_names = bad_names
github google / pytype / pytype / vm.py View on Github external
exc_type: A cfg.Variable of the exception type.

    Returns:
      A tuple of a cfg.Variable of the instantiated type and a list of
      the flattened exception types in the data of exc_type. None takes the
      place of invalid types.
    """
    value = self.program.NewVariable()
    types = []
    for e in exc_type.data:
      if isinstance(e, abstract.Tuple):
        for sub_exc_type in e.pyval:
          sub_value, sub_types = self._instantiate_exception(node, sub_exc_type)
          value.PasteVariable(sub_value)
          types.extend(sub_types)
      elif (isinstance(e, abstract.Instance) and
            e.cls.full_name == "__builtin__.tuple"):
        sub_exc_type = e.get_instance_type_parameter(abstract_utils.T)
        sub_value, sub_types = self._instantiate_exception(node, sub_exc_type)
        value.PasteVariable(sub_value)
        types.extend(sub_types)
      elif isinstance(e, mixin.Class) and any(
          base.full_name == "__builtin__.BaseException" or
          isinstance(base, abstract.AMBIGUOUS_OR_EMPTY) for base in e.mro):
        node, instance = self.init_class(node, e)
        value.PasteVariable(instance)
        types.append(e)
      else:
        if not isinstance(e, abstract.AMBIGUOUS_OR_EMPTY):
          if isinstance(e, mixin.Class):
            mro_seqs = [e.mro] if isinstance(e, mixin.Class) else []
            msg = "%s does not inherit from BaseException" % e.name
github google / pytype / pytype / analyze.py View on Github external
def create_varargs(self, node):
    value = abstract.Instance(self.convert.tuple_type, self)
    value.merge_instance_type_parameter(
        node, abstract_utils.T, self.convert.create_new_unknown(node))
    return value.to_variable(node)
github google / pytype / pytype / vm.py View on Github external
def byte_BUILD_STRING(self, state, op):
    # TODO(mdemello): Test this.
    state, _ = state.popn(op.arg)
    ret = abstract.Instance(self.convert.str_type, self)
    return state.push(ret.to_variable(state.node))
github google / pytype / pytype / abstract.py View on Github external
If this function is part of a class (or has a parent), that parent is
    updated so the change is stored.

    Args:
      defaults_var: a Variable with a single binding to a tuple of default
                    values.
    """
    # Case 1: All given data are tuples constants. Use the longest one.
    if all(isinstance(d, Tuple) for d in defaults_var.data):
      defaults = max((d.pyval for d in defaults_var.data), key=len)
    else:
      # Case 2: Data are entirely Tuple Instances, Unknown or Unsolvable. Make
      # all parameters except self/cls optional.
      # Case 3: Data is anything else. Same as Case 2, but emit a warning.
      if not (all(isinstance(d, (Instance, Unknown, Unsolvable))
                  for d in defaults_var.data) and
              all(d.get_full_name() == "__builtin__.tuple"
                  for d in defaults_var.data if isinstance(d, Instance))):
        self.vm.errorlog.bad_function_defaults(self.vm.frames, self.name)
      # When processing signatures, we'll make a list of the correct size for
      # each signature.
      defaults = None

    new_sigs = []
    for sig in self.signatures:
      if defaults:
        new_sigs.append(sig.set_defaults(defaults))
      else:
        d = sig.param_types
        # If we have a parent, we have a "self" or "cls" parameter. Do NOT make
        # that one optional!
github google / pytype / pytype / abstract.py View on Github external
def __init__(self, cls, vm):
    super(Instance, self).__init__(cls.name, vm)
    self.cls = cls.to_variable(vm.root_cfg_node)
    if (isinstance(cls, (InterpreterClass, PyTDClass)) and
        ("has_dynamic_attributes" in cls or
         "HAS_DYNAMIC_ATTRIBUTES" in cls)):
      self.maybe_missing_members = True
    cls.register_instance(self)
    bad_names = set()
    for base in cls.mro:
      if isinstance(base, ParameterizedClass):
        if isinstance(base, TupleClass):
          if isinstance(self, Tuple):
            # Tuple.__init__ initializes T.
            params = []
          else:
            params = [(T, base.type_parameters[T])]
        elif isinstance(base, Callable):
github google / pytype / pytype / convert.py View on Github external
raise self.TypeParameterError(c.full_name)
            return self.merge_classes(subst[c.full_name].data)
          else:
            return self.constant_to_value(c, subst, self.vm.root_cfg_node)
        elif isinstance(cls, pytd.TupleType):
          content = tuple(self.constant_to_var(abstract_utils.AsInstance(p),
                                               subst, get_node())
                          for p in cls.parameters)
          return abstract.Tuple(content, self.vm)
        elif isinstance(cls, pytd.CallableType):
          clsval = self.constant_to_value(cls, subst, self.vm.root_cfg_node)
          return abstract.Instance(clsval, self.vm)
        else:
          clsval = self.constant_to_value(
              base_cls, subst, self.vm.root_cfg_node)
          instance = abstract.Instance(clsval, self.vm)
          num_params = len(cls.parameters)
          assert num_params <= len(base_cls.template)
          for i, formal in enumerate(base_cls.template):
            if i < num_params:
              node = get_node()
              p = self.constant_to_var(
                  abstract_utils.AsInstance(cls.parameters[i]), subst, node)
            else:
              # An omitted type parameter implies `Any`.
              node = self.vm.root_cfg_node
              p = self.unsolvable.to_variable(node)
            instance.merge_instance_type_parameter(node, formal.name, p)
          return instance
      elif isinstance(cls, pytd.Class):
        assert not cls.template
        # This key is also used in __init__