Skip to content

Commit 5b66ec1

Browse files
authored
bpo-38870: Implement support for ast.FunctionType in ast.unparse (GH-19016)
1 parent ac10e0c commit 5b66ec1

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

Lib/ast.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -741,6 +741,15 @@ def _write_docstring_and_traverse_body(self, node):
741741
def visit_Module(self, node):
742742
self._write_docstring_and_traverse_body(node)
743743

744+
def visit_FunctionType(self, node):
745+
with self.delimit("(", ")"):
746+
self.interleave(
747+
lambda: self.write(", "), self.traverse, node.argtypes
748+
)
749+
750+
self.write(" -> ")
751+
self.traverse(node.returns)
752+
744753
def visit_Expr(self, node):
745754
self.fill()
746755
self.set_precedence(_Precedence.YIELD, node.value)

Lib/test/test_unparse.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -122,10 +122,10 @@ class ASTTestCase(unittest.TestCase):
122122
def assertASTEqual(self, ast1, ast2):
123123
self.assertEqual(ast.dump(ast1), ast.dump(ast2))
124124

125-
def check_ast_roundtrip(self, code1):
126-
ast1 = ast.parse(code1)
125+
def check_ast_roundtrip(self, code1, **kwargs):
126+
ast1 = ast.parse(code1, **kwargs)
127127
code2 = ast.unparse(ast1)
128-
ast2 = ast.parse(code2)
128+
ast2 = ast.parse(code2, **kwargs)
129129
self.assertASTEqual(ast1, ast2)
130130

131131
def check_invalid(self, node, raises=ValueError):
@@ -330,6 +330,14 @@ def test_constant_tuples(self):
330330
ast.Constant(value=(1, 2, 3), kind=None), "(1, 2, 3)"
331331
)
332332

333+
def test_function_type(self):
334+
for function_type in (
335+
"() -> int",
336+
"(int, int) -> int",
337+
"(Callable[complex], More[Complex(call.to_typevar())]) -> None"
338+
):
339+
self.check_ast_roundtrip(function_type, mode="func_type")
340+
333341

334342
class CosmeticTestCase(ASTTestCase):
335343
"""Test if there are cosmetic issues caused by unnecesary additions"""

0 commit comments

Comments
 (0)