]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Reject function def with two signature type comments
authorGuido van Rossum <guido@python.org>
Mon, 28 Jan 2019 19:23:21 +0000 (11:23 -0800)
committerGuido van Rossum <guido@python.org>
Mon, 28 Jan 2019 19:23:21 +0000 (11:23 -0800)
Example:

def foo():  # type: () -> int
    # type: () -> str
    pass

Lib/test/test_type_comments.py
Python/ast.c

index fc55c6845e701023c203f8c756e9735c457e3bd6..6e766361669a4b538537dde611424b1e8af2a00a 100644 (file)
@@ -20,12 +20,17 @@ async def bar():  # type: () -> int
     return await bar()
 """
 
+redundantdef = """\
+def foo():  # type: () -> int
+    # type: () -> str
+    return ''
+"""
+
 forstmt = """\
 for a in []:  # type: int
     pass
 """
 
-
 withstmt = """\
 with context() as a:  # type: int
     pass
@@ -166,6 +171,10 @@ class TypeCommentTests(unittest.TestCase):
         self.assertEqual(tree.body[0].type_comment, None)
         self.assertEqual(tree.body[1].type_comment, None)
 
+    def test_redundantdef(self):
+        with self.assertRaisesRegex(SyntaxError, "^Cannot have two type comments on def"):
+            tree = self.parse(redundantdef)
+
     def test_forstmt(self):
         tree = self.parse(forstmt)
         self.assertEqual(tree.body[0].type_comment, "int")
index 0da33f7a9c0d0001205b3666b209b04c59814e15..4d59344a4aa48cc6e77320d5b46f665d5b7f4e64 100644 (file)
@@ -1752,13 +1752,17 @@ ast_for_funcdef_impl(struct compiling *c, const node *n0,
         return NULL;
     get_last_end_pos(body, &end_lineno, &end_col_offset);
 
-    if (!type_comment && NCH(CHILD(n, name_i + 3)) > 1) {
-        /* If the function doesn't have a type comment on the same line, check
-         * if the suite has a type comment in it. */
+    if (NCH(CHILD(n, name_i + 3)) > 1) {
+        /* Check if the suite has a type comment in it. */
         tc = CHILD(CHILD(n, name_i + 3), 1);
 
-        if (TYPE(tc) == TYPE_COMMENT)
+        if (TYPE(tc) == TYPE_COMMENT) {
+            if (type_comment != NULL) {
+                ast_error(c, n, "Cannot have two type comments on def");
+                return NULL;
+            }
             type_comment = NEW_TYPE_COMMENT(tc);
+        }
     }
 
     if (is_async)