Exemplo n.º 1
0
 def testPrint(self):
     """Smoketests for printing pytd."""
     ast = self.Parse("""
   c1 = ...  # type: int
   T = TypeVar('T')
   class A(typing.Generic[T], object):
     bar = ...  # type: T
     def foo(self, x: list[int], y: T) -> list[T] or float raises ValueError
   X = TypeVar('X')
   Y = TypeVar('Y')
   def bar(x: X or Y) -> ?
 """)
     # TODO(kramm): Do more extensive testing.
     utils.Print(ast, print_format="pytd")
     utils.Print(ast, print_format="pep484stub")
Exemplo n.º 2
0
    def testTypingNameConflict1(self):
        src = textwrap.dedent("""
      import typing

      x = ...  # type: typing.List[str]

      def List() -> None: ...
    """)
        ast = parser.parse_string(src)
        self.assertMultiLineEqual(
            utils.Print(ast).strip("\n"), src.strip("\n"))
Exemplo n.º 3
0
def PrepareForExport(module_name, python_version, ast):
    """Prepare an ast as if it was parsed and loaded.

  External dependencies will not be resolved, as the ast generated by this
  method is supposed to be exported.

  Args:
    module_name: The module_name as a string for the returned ast.
    python_version: A tuple of (major, minor) python version as string
      (see config.python_version).
    ast: pytd.TypeDeclUnit, is only used if src is None.

  Returns:
    A pytd.TypeDeclUnit representing the supplied AST as it would look after
    being written to a file and parsed.
  """
    # This is a workaround for functionality which crept into places it doesn't
    # belong. Ideally this would call some transformation Visitors on ast to
    # transform it into the same ast we get after parsing and loading (compare
    # load_pytd.Loader.load_file). Unfortunately parsing has some special cases,
    # e.g. '__init__' return type and '__new__' being a 'staticmethod', which
    # need to be moved to visitors before we can do this. Printing an ast also
    # applies transformations,
    # e.g. visitors.PrintVisitor._FormatContainerContents, which need to move to
    # their own visitors so they can be applied without printing.
    src = utils.Print(ast)
    ast = pytd_builtins.ParsePyTD(src=src,
                                  module=module_name,
                                  python_version=python_version)
    builtins, _ = pytd_builtins.GetBuiltinsAndTyping()
    ast = ast.Visit(visitors.LookupBuiltins(builtins, full_names=False))
    ast = ast.Visit(visitors.ExpandCompatibleBuiltins(builtins))
    ast = ast.Visit(visitors.LookupLocalTypes())
    ast = ast.Visit(visitors.AdjustTypeParameters())
    ast = ast.Visit(visitors.NamedTypeToClassType())
    ast = ast.Visit(visitors.FillInLocalPointers({"": ast, module_name: ast}))
    ast = ast.Visit(visitors.CanonicalOrderingVisitor())
    return ast
Exemplo n.º 4
0
    def testTypingNameConflict2(self):
        ast = parser.parse_string(
            textwrap.dedent("""
      import typing
      from typing import Any

      x = ...  # type: typing.List[str]

      class MyClass(object):
          List = ...  # type: Any
          x = ...  # type: typing.List[str]
    """))
        expected = textwrap.dedent("""
      import typing
      from typing import Any, List

      x = ...  # type: List[str]

      class MyClass(object):
          List = ...  # type: Any
          x = ...  # type: typing.List[str]
    """)
        self.assertMultiLineEqual(
            utils.Print(ast).strip("\n"), expected.strip("\n"))
Exemplo n.º 5
0
def Print(n, print_format=None):
    """Convert a PYTD node to a string."""
    # TODO(kramm): fix circular import
    from pytype.pytd import utils  # pylint: disable=g-import-not-at-top
    return utils.Print(n, print_format)
Exemplo n.º 6
0
 def testBuiltinAlias(self):
     src = "Number = int"
     ast = parser.parse_string(src)
     self.assertMultiLineEqual(utils.Print(ast), src)
Exemplo n.º 7
0
def _print(t):
    return pytd_utils.Print(t.get_instance_type())