]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-38870: Implement support for ast.FunctionType in ast.unparse (GH-19016)
authorBatuhan Taşkaya <47358913+isidentical@users.noreply.github.com>
Sun, 15 Mar 2020 19:56:57 +0000 (22:56 +0300)
committerGitHub <noreply@github.com>
Sun, 15 Mar 2020 19:56:57 +0000 (19:56 +0000)
Lib/ast.py
Lib/test/test_unparse.py

index 077eb92abb40284d961ce2f2485ec7d36dbe459c..e347d8b9dab1d4df77a16022c2f64c7f787b53c7 100644 (file)
@@ -741,6 +741,15 @@ class _Unparser(NodeVisitor):
     def visit_Module(self, node):
         self._write_docstring_and_traverse_body(node)
 
+    def visit_FunctionType(self, node):
+        with self.delimit("(", ")"):
+            self.interleave(
+                lambda: self.write(", "), self.traverse, node.argtypes
+            )
+
+        self.write(" -> ")
+        self.traverse(node.returns)
+
     def visit_Expr(self, node):
         self.fill()
         self.set_precedence(_Precedence.YIELD, node.value)
index 3d87cfb6daeef888368729e887d06ba169ed8f3e..23292640086b9370b8eccbf8272fde6de95a4ce1 100644 (file)
@@ -122,10 +122,10 @@ class ASTTestCase(unittest.TestCase):
     def assertASTEqual(self, ast1, ast2):
         self.assertEqual(ast.dump(ast1), ast.dump(ast2))
 
-    def check_ast_roundtrip(self, code1):
-        ast1 = ast.parse(code1)
+    def check_ast_roundtrip(self, code1, **kwargs):
+        ast1 = ast.parse(code1, **kwargs)
         code2 = ast.unparse(ast1)
-        ast2 = ast.parse(code2)
+        ast2 = ast.parse(code2, **kwargs)
         self.assertASTEqual(ast1, ast2)
 
     def check_invalid(self, node, raises=ValueError):
@@ -330,6 +330,14 @@ class UnparseTestCase(ASTTestCase):
             ast.Constant(value=(1, 2, 3), kind=None), "(1, 2, 3)"
         )
 
+    def test_function_type(self):
+        for function_type in (
+            "() -> int",
+            "(int, int) -> int",
+            "(Callable[complex], More[Complex(call.to_typevar())]) -> None"
+        ):
+            self.check_ast_roundtrip(function_type, mode="func_type")
+
 
 class CosmeticTestCase(ASTTestCase):
     """Test if there are cosmetic issues caused by unnecesary additions"""