From: Guido van Rossum Date: Mon, 28 Jan 2019 19:23:21 +0000 (-0800) Subject: Reject function def with two signature type comments X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=50a921a0575356ee0d93caaf4a0b118cb316ac63;p=thirdparty%2FPython%2Fcpython.git Reject function def with two signature type comments Example: def foo(): # type: () -> int # type: () -> str pass --- diff --git a/Lib/test/test_type_comments.py b/Lib/test/test_type_comments.py index fc55c6845e70..6e766361669a 100644 --- a/Lib/test/test_type_comments.py +++ b/Lib/test/test_type_comments.py @@ -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") diff --git a/Python/ast.c b/Python/ast.c index 0da33f7a9c0d..4d59344a4aa4 100644 --- a/Python/ast.c +++ b/Python/ast.c @@ -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)