Пример #1
0
def ClassAsType(cls):
    """Converts a pytd.Class to an instance of pytd.Type."""
    params = tuple(item.type_param for item in cls.template)
    if not params:
        return pytd.NamedType(cls.name)
    elif len(params) == 1:
        return pytd.HomogeneousContainerType(pytd.NamedType(cls.name), params)
    else:  # len(cls.template) >= 2
        return pytd.GenericType(pytd.NamedType(cls.name), params)
Пример #2
0
 def p_type_homogeneous(self, p):
     """type : NAME LBRACKET parameters RBRACKET"""
     if len(p[3]) == 1:
         element_type, = p[3]
         p[0] = pytd.HomogeneousContainerType(base_type=pytd.NamedType(
             p[1]),
                                              parameters=(element_type, ))
     else:
         p[0] = pytd.GenericType(base_type=pytd.NamedType(p[1]),
                                 parameters=p[3])
Пример #3
0
def ConvertToType(module, type_node):
  """Helper for converting a type node to a valid Python type.

  Args:
    module: The module to look up symbols/types
    type_node: A type node to convert into a python type

  Returns:
    A valid Python type. Note that None is considered a type in
    the declaration language, but a value in Python. So a string
    None is converted to a NoneType. We use the module object to look
    up potential type definitions defined inside that module.

  Raises:
    TypeError: if the type node passed is not supported/unknown
  """
  # TODO: Convert this to a visitor.

  # clean up str
  if isinstance(type_node, pytd.NamedType):
    if type_node.name == "None":
      return types.NoneType
    elif type_node.name == "generator":
      return types.GeneratorType
    else:
      res = _EvalWithModuleContext(type_node.name, module)
      assert isinstance(res, type), (type_node.name, repr(res))
      return res

  elif isinstance(type_node, pytd.UnionType):
    return pytd.UnionType([ConvertToType(module, t)
                           for t in type_node.type_list])

  elif isinstance(type_node, pytd.IntersectionType):
    return pytd.IntersectionType([ConvertToType(module, t)
                                  for t in type_node.type_list])

  elif isinstance(type_node, pytd.GenericType):
    return pytd.GenericType(ConvertToType(module,
                                          type_node.base_type),
                            type_node.parameters)

  elif isinstance(type_node, pytd.HomogeneousContainerType):
    return pytd.HomogeneousContainerType(ConvertToType(module,
                                                       type_node.base_type),
                                         ConvertToType(module,
                                                       type_node.element_type))

  else:
    raise TypeError("Unknown type of type_node: {!r}".format(type_node))