How to use the pytype.pytd.pytd.Constant 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 / analyze.py View on Github external
combined_types = pytd_utils.JoinTypes(t.to_type(self.exitpoint)
                                              for t in options)
        data.append(pytd.Constant(name, combined_types))
      elif options:
        for option in options:
          try:
            d = option.to_pytd_def(self.exitpoint, name)  # Deep definition
          except NotImplementedError:
            d = option.to_type(self.exitpoint)  # Type only
            if isinstance(d, pytd.NothingType):
              if isinstance(option, abstract.Empty):
                d = pytd.AnythingType()
              else:
                assert isinstance(option, typing_overlay.NoReturn)
          if isinstance(d, pytd.Type) and not isinstance(d, pytd.TypeParameter):
            data.append(pytd.Constant(name, d))
          else:
            data.append(d)
      else:
        log.error("No visible options for %s", name)
        data.append(pytd.Constant(name, pytd.AnythingType()))
    return pytd_utils.WrapTypeDeclUnit("inferred", data)
github google / pytype / pytype / pytd / pytd_utils.py View on Github external
elif isinstance(item, pytd.TypeParameter):
      if item.name in typevars:
        raise NameError("Duplicate top level type parameter: %r" % item.name)
      typevars[item.name] = item
    else:
      raise ValueError("Invalid top level pytd item: %r" % type(item))

  categories = {"function": functions, "class": classes, "constant": constants,
                "alias": aliases, "typevar": typevars}
  for c1, c2 in itertools.combinations(categories, 2):
    _check_intersection(categories[c1], categories[c2], c1, c2)

  return pytd.TypeDeclUnit(
      name=name,
      constants=tuple(
          pytd.Constant(name, t.build())
          for name, t in sorted(constants.items())),
      type_params=tuple(typevars.values()),
      classes=tuple(classes.values()),
      functions=tuple(functions.values()),
      aliases=tuple(aliases.values()))
github google / pytype / pytype / pytd / parse / parser.py View on Github external
kind = pytd.METHOD
      decorators = name_to_decorators[name]
      if "classmethod" in decorators:
        kind = pytd.CLASSMETHOD
      if name == "__new__" or "staticmethod" in decorators:
        kind = pytd.STATICMETHOD
      if name_external[name][True]:
        methods.append(pytd.ExternalFunction(name, (), kind))
      else:
        methods.append(pytd.Function(name, tuple(signatures), kind))

    constants = []
    for name, property_type in name_to_property_type.items():
      if not property_type:
        property_type = pytd.AnythingType()
      constants.append(pytd.Constant(name, property_type))

    return methods, constants
github google / pytype / pytype / abstract.py View on Github external
starstarargs,
                       return_type=Unknown._to_pytd(node, ret),
                       exceptions=(),
                       template=())
        for args, _, ret in self._calls))
    if calls:
      methods = (pytd.Function("__call__", calls, pytd.METHOD),)
    else:
      methods = ()
    # TODO(rechen): Should we convert self.cls to a metaclass here as well?
    return pytd.Class(
        name=class_name,
        metaclass=None,
        parents=(pytd.NamedType("__builtin__.object"),),
        methods=methods,
        constants=tuple(pytd.Constant(name, Unknown._to_pytd(node, c))
                        for name, c in self.members.items()),
        slots=None,
        template=())
github google / pytype / pytype / pytd / parse / parser.py View on Github external
def p_constantdef_pep526_ellipsis(self, p):
    """constantdef : NAME COLON type ASSIGN ELLIPSIS"""
    p[0] = pytd.Constant(p[1], p[3])
github google / pytype / pytype / output.py View on Github external
# This happens if a module does e.g. "from x import y as z", i.e., copies
      # something from another module to the local namespace. We *could*
      # reproduce the entire class, but we choose a more dense representation.
      return v.to_type(node)
    elif isinstance(v, abstract.PyTDClass):  # a namedtuple instance
      assert name != v.name
      return pytd.Alias(name, pytd.NamedType(v.name))
    elif isinstance(v, abstract.InterpreterClass):
      if v.official_name is None or name == v.official_name:
        return self._class_to_def(node, v, name)
      else:
        return pytd.Alias(name, pytd.NamedType(v.official_name))
    elif isinstance(v, abstract.TypeParameter):
      return self._typeparam_to_def(node, v, name)
    elif isinstance(v, abstract.Unsolvable):
      return pytd.Constant(name, v.to_type(node))
    else:
      raise NotImplementedError(v.__class__.__name__)
github google / pytype / pytype / pytd / parse / parser.py View on Github external
prev_list = self.generated_classes[base_name]
    name_dedup = "~%d" % len(prev_list) if prev_list else ""
    class_name = "`%s%s`" % (base_name, name_dedup)

    # Like for typing.Tuple, heterogeneous NamedTuples get converted to
    # homogeneous ones:
    # NamedTuple[("x", X), ("y", Y)] -> Tuple[X, Y] -> Tuple[Union[X, Y], ...]
    types = tuple(t for _, t in fields)
    container_param = (pytd.UnionType(type_list=types) if types
                       else pytd.AnythingType())

    class_parent = pytd.HomogeneousContainerType(
        base_type=pytd.NamedType("tuple"),
        parameters=(container_param,))

    class_constants = tuple(pytd.Constant(n, t) for n, t in fields)
    nt_class = pytd.Class(name=class_name,
                          metaclass=None,
                          parents=(class_parent,),
                          methods=(),
                          constants=class_constants,
                          template=())

    self.generated_classes[base_name].append(nt_class)
    p[0] = pytd.NamedType(nt_class.name)
github google / pytype / pytype / pytd / parse / parser.py View on Github external
def p_constantdef_ellipsis(self, p):
    """constantdef : NAME ASSIGN ELLIPSIS"""
    p[0] = pytd.Constant(p[1], pytd.AnythingType())
github google / pytype / pytype / analyze.py View on Github external
def pytd_for_types(self, defs):
    data = []
    pytd_convert = self.convert.pytd_convert
    annots = pytd_convert.get_annotations_dict(defs)
    for name, t in pytd_convert.uninitialized_annotations_to_instance_types(
        self.exitpoint, annots, defs):
      data.append(pytd.Constant(name, t))
    for name, var in defs.items():
      if name in output.TOP_LEVEL_IGNORE or self._is_builtin(name, var.data):
        continue
      options = []
      for value, is_annotation in pytd_convert.get_annotated_values(
          self.exitpoint, name, var, annots):
        if is_annotation:
          data.append(pytd.Constant(name, value))
        else:
          options.append(value)
      if (len(options) > 1 and
          not all(isinstance(o, abstract.FUNCTION_TYPES) for o in options)):
        # It's ambiguous whether this is a type, a function or something
        # else, so encode it as a constant.
        combined_types = pytd_utils.JoinTypes(t.to_type(self.exitpoint)
                                              for t in options)
        data.append(pytd.Constant(name, combined_types))
      elif options:
        for option in options:
          try:
            d = option.to_pytd_def(self.exitpoint, name)  # Deep definition
          except NotImplementedError:
            d = option.to_type(self.exitpoint)  # Type only
            if isinstance(d, pytd.NothingType):